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

后端 未结 16 639
一个人的身影
一个人的身影 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:20

    @dogbane has a nice simple answer for removing leading empty lines. Here's a simple awk command which removes just the trailing lines. Use this with @dogbane's sed command to remove both leading and trailing blanks.

    awk '{ LINES=LINES $0 "\n"; } /./ { printf "%s", LINES; LINES=""; }'
    

    This is pretty simple in operation.

    • Add every line to a buffer as we read it.
    • For every line which contains a character, print the contents of the buffer and then clear it.

    So the only things that get buffered and never displayed are any trailing blanks.

    I used printf instead of print to avoid the automatic addition of a newline, since I'm using newlines to separate the lines in the buffer already.

提交回复
热议问题