Delete \n characters from line range in text file

后端 未结 4 1141
春和景丽
春和景丽 2021-01-29 05:07

Let\'s say we have a text file with 1000 lines.

How can we delete new line characters from line 20 to 500 (replace them with space for example)?

My try:

4条回答
  •  庸人自扰
    2021-01-29 05:50

    You could use something like this (my example is on a slightly smaller scale :-)

    $ cat file
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    $ awk '{printf "%s%s", $0, (2<=NR&&NR<=5?FS:RS)}' file
    1
    2 3 4 5 6
    7
    8
    9
    10
    

    The second %s in the printf format specifier is replaced by either the Field Separator (a space by default) or the Record Separator (a newline) depending on whether the Record Number is within the range.

    Alternatively:

    $ awk '{ORS=(2<=NR&&NR<=5?FS:RS)}1' file
    1
    2 3 4 5 6
    7
    8
    9
    10
    

    Change the Output Record Separator depending on the line number and print every line.

    You can pass variables for the start and end if you want, using awk -v start=2 -v end=5 '...'

提交回复
热议问题