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?
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.
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.
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.
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.
echo "" >> file.txt
Adds a newline character at the end
With sed
:
sed -i '' -e '$a\' file.txt
with echo
:
echo >> file.txt
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
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin14)
echo \ >> file.txt
This worked for me.
sed -i -z 's/$/\n/g' file.txt
This works on centos the empty string above didn't.
sed -i -e '$a\' file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With