Delete \n characters from line range in text file

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

提交回复
热议问题