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

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

    This AWK script will do the trick:

    BEGIN {
        ne=0;
    }
    
    /^[[:space:]]*$/ {
        ne++;
    }
    
    /[^[:space:]]+/ {
        for(i=0; i < ne; i++)
            print "";
        ne=0;
        print
    }
    

    The idea is simple: empty lines do not get echoed immediately. Instead, we wait till we get a non-empty line, and only then we first echo out as much empty lines as seen before it, and only then echo out the new non-empty line.

提交回复
热议问题