Delete \n characters from line range in text file

后端 未结 4 1138
春和景丽
春和景丽 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:26

    Here's a perl version:

    my $min = 5; my $max = 10;
    while (<DATA>) {
        if ($. > $min && $. < $max) {
            chomp;
            $_ .= " ";
        }
        print;
    }
    
    __DATA__
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    

    Output:

    1
    2
    3
    4
    5
    6 7 8 9 10
    11
    12
    13
    14
    15
    

    It reads in DATA (which you can set to being a filehandle or whatever your application requires), and checks the line number, $.. While the line number is between $min and $max, the line ending is chomped off and a space added to the end of the line; otherwise, the line is printed as-is.

    0 讨论(0)
  • 2021-01-29 05:41

    Using a perl one-liner to strip the newline:

    perl -i -pe 'chomp if 20..500' file
    

    Or to replace it with a space:

    perl -i -pe 's/\R/ / if 20..500' file
    

    Explanation:

    Switches:

    • -i: Edit <> files in place (makes backup if extension supplied)
    • -p: Creates a while(<>){...; print} loop for each “line” in your input file.
    • -e: Tells perl to execute the code on command line.

    Code:

    • chomp: Remove new line
    • 20 .. 500: if Range operator .. is between line numbers 20 to 500
    0 讨论(0)
  • 2021-01-29 05:48

    This might work for you (GNU sed):

    sed -r '20,500{N;s/^(.*)(\n)/\2\1 /;D}' file
    

    or perhaps more readably:

    sed ':a;20,500{N;s/\n/ /;ta}' file
    
    0 讨论(0)
  • 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 '...'

    0 讨论(0)
提交回复
热议问题