3

I wanted to append a new line to the end of a file, but some of the files I'm working with may not contain newline characters as their last character, which means I'm appending onto the same line.

Is there an easy way to check for newline characters, and adjust accordingly?

echo "some line of text" >> aFile.txt

1 Answer 1

9

You can use:

x=$(tail -c 1 aFile.txt)
if [ "$x" != "" ]
then echo >> aFile.txt
fi
echo "some line of text" >> aFile.txt

The $(...) operator removes the trailing newline from the output of the command embedded in it, and the tail -c 1 command prints the last character of the file. If the last character is not a newline, then the string "$x" won't be empty, so append a newline to the file before appending the new line of text.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.