Add a newline only if it doesn't exist

前端 未结 8 602
温柔的废话
温柔的废话 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:16

    Since it removes newline if it's not there, you could simply use:

    echo "" >> file;  sed -ie '/^$/d;$G' file; sed -ie '/^$/d;$G' file
    

    Adds a newline and removes everything then adds newline. Not the elegant way, but certainly works :)

    0 讨论(0)
  • 2021-01-31 09:18

    Try using vi or ex:

    ex -scwq foo.txt
    

    or for multiple files:

    vi -es +"bufdo wq" *.txt
    ex -s +"bufdo wq" *.txt
    

    which automatically adds EOL at EOF on file save if it's missing.

    To apply for certain files recursively, use a new globbing option (**) such as **/*.txt (enable by shopt -s globstar).

    0 讨论(0)
提交回复
热议问题