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

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

    In bash, using cat, wc, grep, sed, tail and head:

    # number of first line that contains non-empty character
    i=`grep -n "^[^\B*]"  | sed -e 's/:.*//' | head -1`
    # number of hte last one
    j=`grep -n "^[^\B*]"  | sed -e 's/:.*//' | tail -1`
    # overall number of lines:
    k=`cat  | wc -l`
    # how much empty lines at the end of file we have?
    m=$(($k-$j))
    # let strip last m lines!
    cat  | head -n-$m
    # now we have to strip first i lines and we are done 8-)
    cat  | tail -n+$i
    

    Man, it's definitely worth to learn "real" programming language to avoid that ugliness!

提交回复
热议问题