I want to add a newline at the end of a file only if it doesn't exist. This is to prevent multiple newlines at the end of the file.
I'm hoping to use sed
. Here are the issues I'm having with my current code:
sed -i -e '/^$/d;$G' /inputfile echo file1 name1 name2 echo file2 name3 name4 (newline)
when I run my code on to the files;
echo file1 name1 name2 (newline) echo file2 name3 name4
it adds a newline if it doesn't have one but removes it if it exists... this puzzles me.
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.
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.
Assuming that the file does not already end in a newline and you simply want to append some more text without adding one, you can use the -n argument, e.g. However, some UNIX systems do not provide this option; if that is the case you can use printf , e.g. Do not print the trailing newline character.
The sed command can add a new line after a pattern match is found. The "a" command to sed tells it to add a new line after a match is found. The sed command can add a new line before a pattern match is found. The "i" command to sed tells it to add a new line before a match is found.
GNU:
sed -i '$a\' *.txt
OS X:
sed -i '' '$a\' *.txt
$
addresses the last line. a\
is the append function.
sed -i '' -n p *.txt
-n
disables printing and p
prints the pattern space. p
adds a missing newline in OS X's sed but not in GNU sed, so this doesn't work with GNU sed.
awk 1
1
can be replaced with anything that evaluates to true. Modifying a file in place:
{ rm file;awk 1 >file; }<file
[[ $(tail -c1 file) && -f file ]]&&echo ''>>file
Trailing newlines are removed from the result of the command substitution, so $(tail -c1 file)
is empty only if file
ends with a linefeed or is empty. -f file
is false if file
is empty. [[ $x ]]
is equivalent to [[ -n $x ]]
in bash.
Rather than processing the whole file with see just to add a newline at the end, just check the last character and if it's not a newline, append one. Testing for newline is slightly interesting, since the shell will generally trim them from the end of strings, so I append "x" to protect it:
if [ "$(tail -c1 "$inputfile"; echo x)" != $'\nx' ]; then echo "" >>"$inputfile" fi
Note that this will append newline to empty files, which might not be what you want. If you want to leave empty files alone, add another test:
if [ -s "$inputfile" ] && [ "$(tail -c1 "$inputfile"; echo x)" != $'\nx' ]; then echo "" >>"$inputfile" fi
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