I have files that end in one or more newlines and should end in only one newline. How can I do that with Bash/Unix/GNU tools?
Example bad file:
1\n \n 2\n \n \n 3\n \n \n \n Example corrected file:
1\n \n 2\n \n \n 3\n In other words: There should be exactly one newline between the EOF and the last non-newline character of the file.
Reference Implementation
Read file contents, chop off a single newline till there no further two newlines at the end, write it back:
#! /bin/python import sys with open(sys.argv[1]) as infile: lines = infile.read() while lines.endswith("\n\n"): lines = lines[:-1] with open(sys.argv[2], 'w') as outfile: for line in lines: outfile.write(line) Clarification: Of course, piping is allowed, if that is more elegant.