Add a newline only if it doesn't exist

前端 未结 8 695
温柔的废话
温柔的废话 2021-01-31 08:49

I want to add a newline at the end of a file only if it doesn\'t exists, this is to prevent multiple newlines at the end of the file.

I\'m hoping to use sed. Here\'s the

8条回答
  •  自闭症患者
    2021-01-31 09:04

    sed

    GNU:

    sed -i '$a\' *.txt
    

    OS X:

    sed -i '' '$a\' *.txt
    

    $ addresses the last line. a\ is the append function.

    OS X's sed

    sed -i '' -n p *.txt
    

    -n disables printing and p prints the pattern space. p adds a missing newline in OS X's sed but not in GNU sed, so this doesn't work with GNU sed.

    awk

    awk 1
    

    1 can be replaced with anything that evaluates to true. Modifying a file in place:

    { rm file;awk 1 >file; }

    bash

    [[ $(tail -c1 file) && -f file ]]&&echo ''>>file
    

    Trailing newlines are removed from the result of the command substitution, so $(tail -c1 file) is empty only if file ends with a linefeed or is empty. -f file is false if file is empty. [[ $x ]] is equivalent to [[ -n $x ]] in bash.

提交回复
热议问题