Add a newline only if it doesn't exist

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

    Rather than processing the whole file with see just to add a newline at the end, just check the last character and if it's not a newline, append one. Testing for newline is slightly interesting, since the shell will generally trim them from the end of strings, so I append "x" to protect it:

    if [ "$(tail -c1 "$inputfile"; echo x)" != $'\nx' ]; then
        echo "" >>"$inputfile"
    fi
    

    Note that this will append newline to empty files, which might not be what you want. If you want to leave empty files alone, add another test:

    if [ -s "$inputfile" ] && [ "$(tail -c1 "$inputfile"; echo x)" != $'\nx' ]; then
        echo "" >>"$inputfile"
    fi
    

提交回复
热议问题