I have some files that I'd like to delete the last newline if it is the last character in a file. od -c
shows me that the command I run does write the file with a trailing new line:
0013600 n t > \n
I've tried a few tricks with sed but the best I could think of isn't doing the trick:
sed -e '$s/\(.*\)\n$/\1/' abc
Any ideas how to do this?
This is a good solution if you need it to work with pipes/redirection instead of reading/output from or to a file. This works with single or multiple lines. It works whether there is a trailing newline or not.
Details:
head -c -1
truncates the last character of the string, regardless of what the character is. So if the string does not end with a newline, then you would be losing a character.sed '$s/$//'
. The first$
means only apply the command to the last line.s/$//
means substitute the "end of the line" with "nothing", which is basically doing nothing. But it has a side effect of adding a trailing newline is there isn't one.Note: Mac's default
head
does not support the-c
option. You can dobrew install coreutils
and useghead
instead.Using dd:
The only time I've wanted to do this is for code golf, and then I've just copied my code out of the file and pasted it into an
echo -n 'content'>file
statement.Yet another perl WTDI:
Edit 2:Here is anawk
version (corrected) that doesn't accumulate a potentially huge array:awk '{if (line) print line; line=$0} END {printf $0}' abcPOSIX SED:
'${/^$/d}'