比赛迟到了,这是我在 Python 中的 sed 实现:
import re
import shutil
from tempfile import mkstemp
def sed(pattern, replace, source, dest=None, count=0):
"""Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
Args:
pattern (str): pattern to match (can be re.pattern)
replace (str): replacement str
source (str): input filename
count (int): number of occurrences to replace
dest (str): destination filename, if not given, source will be over written.
"""
fin = open(source, 'r')
num_replaced = count
if dest:
fout = open(dest, 'w')
else:
fd, name = mkstemp()
fout = open(name, 'w')
for line in fin:
out = re.sub(pattern, replace, line)
fout.write(out)
if out != line:
num_replaced += 1
if count and num_replaced > count:
break
try:
fout.writelines(fin.readlines())
except Exception as E:
raise E
fin.close()
fout.close()
if not dest:
shutil.move(name, source)
例子:
sed('foo', 'bar', "foo.txt")
将 foo.txt 中的所有 'foo' 替换为 'bar'
sed('foo', 'bar', "foo.txt", "foo.updated.txt")
将所有 'foo' 替换为 'foo.txt' 中的 'bar' 并将结果保存在 "foo.updated.txt" 中。
sed('foo', 'bar', "foo.txt", count=1)
将仅将第一次出现的 'foo' 替换为 'bar' 并将结果保存在原始文件 'foo.txt' 中