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

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

    From Useful one-line scripts for sed:

    # Delete all leading blank lines at top of file (only).
    sed '/./,$!d' file
    
    # Delete all trailing blank lines at end of file (only).
    sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' file
    

    Therefore, to remove both leading and trailing blank lines from a file, you can combine the above commands into:

    sed -e :a -e '/./,$!d;/^\n*$/{$d;N;};/\n$/ba' file
    

提交回复
热议问题