Removing trailing / starting newlines with sed, awk, tr, and friends

后端 未结 16 662
一个人的身影
一个人的身影 2021-01-30 21:04

I would like to remove all of the empty lines from a file, but only when they are at the end/start of a file (that is, if there are no non-empty lines before them, at the start;

16条回答
  •  无人及你
    2021-01-30 21:25

    Here's an awk version that removes trailing blank lines (both empty lines and lines consisting of nothing but white space).

    It is memory efficient; it does not read the entire file into memory.

    awk '/^[[:space:]]*$/ {b=b $0 "\n"; next;} {printf "%s",b; b=""; print;}'
    

    The b variable buffers up the blank lines; they get printed when a non-blank line is encountered. When EOF is encountered, they don't get printed. That's how it works.

    If using gnu awk, [[:space:]] can be replaced with \s. (See full list of gawk-specific Regexp Operators.)

    If you want to remove only those trailing lines that are empty, see @AndyMortimer's answer.

提交回复
热议问题