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

后端 未结 16 802
一个人的身影
一个人的身影 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条回答
  •  萌比男神i
    2021-01-30 21:19

    Here's an adapted sed version, which also considers "empty" those lines with just spaces and tabs on it.

    sed -e :a -e '/[^[:blank:]]/,$!d; /^[[:space:]]*$/{ $d; N; ba' -e '}'
    

    It's basically the accepted answer version (considering BryanH comment), but the dot . in the first command was changed to [^[:blank:]] (anything not blank) and the \n inside the second command address was changed to [[:space:]] to allow newlines, spaces an tabs.

    An alternative version, without using the POSIX classes, but your sed must support inserting \t and \n inside […]. GNU sed does, BSD sed doesn't.

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

    Testing:

    prompt$ printf '\n \t \n\nfoo\n\nfoo\n\n \t \n\n' 
    
    
    
    foo
    
    foo
    
    
    
    prompt$ printf '\n \t \n\nfoo\n\nfoo\n\n \t \n\n' | sed -n l
    $
     \t $
    $
    foo$
    $
    foo$
    $
     \t $
    $
    prompt$ printf '\n \t \n\nfoo\n\nfoo\n\n \t \n\n' | sed -e :a -e '/[^[:blank:]]/,$!d; /^[[:space:]]*$/{ $d; N; ba' -e '}'
    foo
    
    foo
    prompt$
    

提交回复
热议问题