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

后端 未结 16 686
一个人的身影
一个人的身影 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
    慢半拍i (楼主)
    2021-01-30 21:23

    As mentioned in another answer, tac is part of coreutils, and reverses a file. Combining the idea of doing it twice with the fact that command substitution will strip trailing new lines, we get

    echo "$(echo "$(tac "$filename")" | tac)"
    

    which doesn't depend on sed. You can use echo -n to strip the remaining trailing newline off.

提交回复
热议问题