Add a newline only if it doesn't exist

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

    tail -c1 file | read -r _ || echo >> file
    

    gets the last character of the file pipes it into read, which will exit with a nonzero exit code if it encounters EOF before newline (so, if the last character of the file isn't a newline). If read exits nonzero, then append a newline onto the file using echo (if read exits 0, that satisfies the ||, so the echo command isn't run).

    From http://backreference.org/2010/05/23/sanitizing-files-with-no-trailing-newline/.

提交回复
热议问题