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

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

    here's a one-pass solution in awk: it does not start printing until it sees a non-empty line and when it sees an empty line, it remembers it until the next non-empty line

    awk '
        /[[:graph:]]/ {
            # a non-empty line
            # set the flag to begin printing lines
            p=1      
            # print the accumulated "interior" empty lines 
            for (i=1; i<=n; i++) print ""
            n=0
            # then print this line
            print
        }
        p && /^[[:space:]]*$/ {
            # a potentially "interior" empty line. remember it.
            n++
        }
    ' filename
    

    Note, due to the mechanism I'm using to consider empty/non-empty lines (with [[:graph:]] and /^[[:space:]]*$/), interior lines with only whitespace will be truncated to become truly empty.

提交回复
热议问题