'endofline' 'eol' boolean (default on)
local to buffer
{not in Vi}
When writing a file and this option is off and the 'binary' option
is on, no <EOL> will be written for the last line in the file. This
option is automatically set when starting to edit a new file, unless
the file does not have an <EOL> for the last line in the file, in
which case it is reset.
#!/usr/bin/python
# a filter that strips newline from last line of its stdin
# if the last line is empty, leave it as-is, to make the operation idempotent
# inspired by: https://stackoverflow.com/questions/1654021/how-can-i-delete-a-newline-if-it-is-the-last-character-in-a-file/1663283#1663283
import sys
if __name__ == '__main__':
try:
pline = sys.stdin.next()
except StopIteration:
# no input, nothing to do
sys.exit(0)
# spit out all but the last line
for line in sys.stdin:
sys.stdout.write(pline)
pline = line
# strip newline from last line before spitting it out
if len(pline) > 2 and pline.endswith("\r\n"):
sys.stdout.write(pline[:-2])
elif len(pline) > 1 and pline.endswith("\n"):
sys.stdout.write(pline[:-1])
else:
sys.stdout.write(pline)