If all you want to do is add text to the last line, it's very easy with sed. Replace $
(pattern matching at the end of the line) by the text you want to add, only on lines in the range $
(which means the last line).
sed '$ s/$/ and Linux/' <file >file.new &&
mv file.new file
which on Linux can be shortened to
sed -i '$ s/$/ and Linux/' file
If you want to remove the last byte in a file, Linux (more precisely GNU coreutils) offers the truncate
command, which makes this very easy.
truncate -s -1 file
A POSIX way to do it is with dd
. First determine the file length, then truncate it to one byte less.
length=$(wc -c <file)
dd if=/dev/null of=file obs="$((length-1))" seek=1
Note that both of these unconditionally truncate the last byte of the file. You may want to check that it's a newline first:
length=$(wc -c <file)
if [ "$length" -ne 0 ] && [ -z "$(tail -c -1 <file)" ]; then
# The file ends with a newline or null
dd if=/dev/null of=file obs="$((length-1))" seek=1
fi
sed '$s/$/ and linux/'