Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new line character at the end of file in bash

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?

like image 439
Do Thanh Tung Avatar asked Apr 14 '14 08:04

Do Thanh Tung


People also ask

How do I go to a new line at the end of a file in bash?

Sometimes we need to work with a file for programming purposes, and the new line requires to add at the end of the file. This appending task can be done by using 'echo' and 'tee' commands. Using '>>' with 'echo' command appends a line to a file.

How do I add a line to the end of a file in Linux?

Append Text Using >> Operator Alternatively, you can use the printf command (do not forget to use \n character to add the next line). You can also use the cat command to concatenate text from one or more files and append it to another file.

How do I add a new line in bash?

use ctrl-v ctrl-m key combos twice to insert two newline control character in the terminal. Ctrl-v lets you insert control characters into the terminal. You could use the enter or return key instead of the ctrol-m if you like. It inserts the same thing.

How do you end a file with a newline?

The last line (like all lines) needs an \n to end it. An \n at the end of the file doesn't create an additional line. Sometimes, however, text editors will add a visible blank line there.


6 Answers

echo "" >> file.txt

Adds a newline character at the end

like image 182
a5hk Avatar answered Oct 22 '22 18:10

a5hk


With sed:

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

with echo:

echo  >> file.txt
like image 33
MLSC Avatar answered Oct 22 '22 19:10

MLSC


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

like image 20
kenorb Avatar answered Oct 22 '22 20:10

kenorb


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

echo \ >> file.txt
like image 35
jusopi Avatar answered Oct 22 '22 19:10

jusopi


This worked for me.

sed -i -z 's/$/\n/g' file.txt
like image 32
web Avatar answered Oct 22 '22 19:10

web


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

sed -i -e '$a\' file
like image 28
GarethReid Avatar answered Oct 22 '22 20:10

GarethReid