Add new line character at the end of file in bash

82,942

Solution 1

echo "" >> file.txt

Adds a newline character at the end

Solution 2

With sed:

sed -i '' -e '$a\' file.txt

with echo:

echo  >> file.txt

Solution 3

Use Vi which automatically creates EOL at EOF on file save.

For example:

vi -escwq foo.txt

or:

ex -scwq foo.txt

To correct multiple files, check: How to fix 'No newline at end of file' for lots of files? at SO

Solution 4

GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14)

echo \ >> file.txt

Solution 5

This worked for me.

sed -i -z 's/$/\n/g' file.txt
Share:
82,942
Do Thanh Tung
Author by

Do Thanh Tung

Updated on July 09, 2022

Comments

  • Do Thanh Tung
    Do Thanh Tung about 1 year

    How can I use bash command line to add new line character at the end of file named file.txt. I tried use echo but it's not right. Can you show me how can I do it?

  • twalberg
    twalberg over 9 years
    I don't think that awk one is right. That will create a file for each line of file.txt that is named after the contents of that line, and containing a single newline...
  • T. Brian Jones
    T. Brian Jones about 7 years
    Extremely simple and extremely fast, even on very large files. >> seems to always be fast for appending.
  • Anthony Geoghegan
    Anthony Geoghegan almost 7 years
    That adds a space character as well as a line-feed character.
  • jusopi
    jusopi almost 7 years
    ah yes, you're right. It appends the space to the line before the new line. Good catch.
  • Boris Verkhovskiy
    Boris Verkhovskiy over 1 year
    echo >> file.txt works too, you don't need the "" part.
  • CervEd
    CervEd over 1 year
    sed -i '$a\' file.txt is sufficient
  • villasv
    villasv over 1 year
    @CervEd -i '' is for Mac users, -i for everyone else