文本搜索和替换

文本搜索和替换

我想要搜索并用以下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='')

相关内容