对我来说,发布的解决方案看起来有些神秘。这是Python 3.6中的解决方案:
#!/usr/bin/env python3
from pathlib import Path
import sys
import fileinput
def remove_multiple_blank_lines_from_file(path, strip_right=True):
non_blank_lines_out_of_two_last_lines = [True, True]
for line in fileinput.input(str(path), inplace=True):
non_blank_lines_out_of_two_last_lines.pop(0)
non_blank_lines_out_of_two_last_lines.append(bool(line.strip()))
if sum(non_blank_lines_out_of_two_last_lines) > 0:
line_to_write = line.rstrip() + '\n' if strip_right else line
sys.stdout.write(line_to_write)
def remove_multiple_blank_lines_by_glob(rglob='*', path=Path('.'), strip_right=True):
for p in path.rglob(rglob):
if p.is_file():
try:
remove_multiple_blank_lines_from_file(p, strip_right=strip_right)
except Exception as e:
print(f"File '{p}' was not processed due the error: {e}")
if __name__ == '__main__':
remove_multiple_blank_lines_by_glob(sys.argv[1], Path(sys.argv[2]), next(iter(sys.argv[3:]), None) == '--strip-right')
您可以从解释器调用函数,也可以从外壳运行它,例如:
$ ./remove_multiple_lines.py '*' /tmp/ --strip-right