Add new line character at the end of file in bash

BashFileCommandNewline

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

echo "" >> file.txt

Adds a newline character at the end

Solution 2 - Bash

With sed:

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

with echo:

echo  >> file.txt

Solution 3 - Bash

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 - Bash

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

echo \ >> file.txt

Solution 5 - Bash

This worked for me.

sed -i -z 's/$/\n/g' file.txt

Solution 6 - Bash

This works on centos the empty string above didn't.

sed -i -e '$a\' file

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDo Thanh TungView Question on Stackoverflow
Solution 1 - Basha5hkView Answer on Stackoverflow
Solution 2 - BashMLSCView Answer on Stackoverflow
Solution 3 - BashkenorbView Answer on Stackoverflow
Solution 4 - BashjusopiView Answer on Stackoverflow
Solution 5 - BashwebView Answer on Stackoverflow
Solution 6 - BashGarethReidView Answer on Stackoverflow