Chris
Chris

Reputation: 4794

Appending a new line to a file, checking whether last character is a newline character or not in Bash

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

Upvotes: 3

Views: 1934

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 755006

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.

Upvotes: 10

Related Questions