![文本搜索和替换](https://linux22.com/image/900496/%E6%96%87%E6%9C%AC%E6%90%9C%E7%B4%A2%E5%92%8C%E6%9B%BF%E6%8D%A2.png)
我想要搜索并用以下file2.txt
值替换中的值:file1.txt
file1.txt
:
A value1
B value2
C value3
D value4
E value5
F value6
file2.txt
:
A
value6
E
B
value3
求购output.txt
:
value1
value6
value5
value2
value3
答案1
在我看来,这个密钥对替换最好以脚本的形式完成,除非您想要命令行流解决方案作为挑战。脚本将允许将来的泛化。例如,在 Python 中它看起来如下:
#!/usr/bin/python3
map = {}
with open('file1.txt') as f:
for line in f:
t = line.split()
map[t[0]] = t[1]
with open('file2.txt') as f:
for line in f:
t = line.split()
if t[0] in map: print(map[t[0]])
else: print(line, end='')