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

Author by
Do Thanh Tung
Updated on July 09, 2022Comments
-
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 useecho
but it's not right. Can you show me how can I do it? -
twalberg over 9 yearsI don't think that
awk
one is right. That will create a file for each line offile.txt
that is named after the contents of that line, and containing a single newline... -
T. Brian Jones about 7 yearsExtremely simple and extremely fast, even on very large files.
>>
seems to always be fast for appending. -
Anthony Geoghegan almost 7 yearsThat adds a space character as well as a line-feed character.
-
jusopi almost 7 yearsah yes, you're right. It appends the space to the line before the new line. Good catch.
-
Boris Verkhovskiy over 1 year
echo >> file.txt
works too, you don't need the""
part. -
CervEd over 1 year
sed -i '$a\' file.txt
is sufficient -
villasv over 1 year@CervEd
-i ''
is for Mac users,-i
for everyone else