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?
Here is a nice, tidy Python solution. I made no attempt to be terse here.
This modifies the file in-place, rather than making a copy of the file and stripping the newline from the last line of the copy. If the file is large, this will be much faster than the Perl solution that was chosen as the best answer.
It truncates a file by two bytes if the last two bytes are CR/LF, or by one byte if the last byte is LF. It does not attempt to modify the file if the last byte(s) are not (CR)LF. It handles errors. Tested in Python 2.6.
Put this in a file called "striplast" and
chmod +x striplast
.P.S. In the spirit of "Perl golf", here's my shortest Python solution. It slurps the whole file from standard input into memory, strips all newlines off the end, and writes the result to standard output. Not as terse as the Perl; you just can't beat Perl for little tricky fast stuff like this.
Remove the "\n" from the call to
.rstrip()
and it will strip all white space from the end of the file, including multiple blank lines.Put this into "slurp_and_chomp.py" and then run
python slurp_and_chomp.py < inputfile > outputfile
.Should remove any last occurence of \n in file. Not working on huge file (due to sed buffer limitation)
I had a similar problem, but was working with a windows file and need to keep those CRLF -- my solution on linux:
or, to edit the file in place:
[Editor's note:
-pi -e
was originally-pie
, but, as noted by several commenters and explained by @hvd, the latter doesn't work.]This was described as a 'perl blasphemy' on the awk website I saw.
But, in a test, it worked.
If you want to do it right, you need something like this:
We open the file for reading and appending; opening for appending means that we are already
seek
ed to the end of the file. We then get the numerical position of the end of the file withtell
. We use that number to seek back one character, and then we read that one character. If it's a newline, we truncate the file to the character before that newline, otherwise, we do nothing.This runs in constant time and constant space for any input, and doesn't require any more disk space, either.