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\n2\n\n\n3\n\n\n\nExample corrected file:1\n\n2\n\n\n3\nIn other words: There should be exactly one newline between the EOF and the last non-newline character of the file.Reference ImplementationRead file contents, chop off a single newline till there no further two newlines at the end, write it back:#! /bin/pythonimport syswith 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.
How to remove multiple newlines at EOF?
bash;sed;awk;ed
awk '/^$/ {nlstack=nlstack \n;next;} {printf %s,nlstack; nlstack=; print;}' file