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

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

    So I'm going to borrow part of @dogbane's answer for this, since that sed line for removing the leading blank lines is so short...

    tac is part of coreutils, and reverses a file. So do it twice:

    tac file | sed -e '/./,$!d' | tac | sed -e '/./,$!d'
    

    It's certainly not the most efficient, but unless you need efficiency, I find it more readable than everything else so far.

提交回复
热议问题