我有两个文件,分别是 A.txt 和 B.txt。 A.txt 有如下所示的三列
0 0 17
0 1 17
0 2 4
0 3 50
0 4 90
....
....
我必须用保存在 B.txt 中的相应 map 值替换第三列值,如下所示
1 1
2 1
3 1
4 1
..
17 5
..
50 8
..
90 11
..
B.txt中第一列的值和A.txt中第三列的值相同,我需要创建一个新文件(比如C.txt),其前两列与A.txt相同A.txt 但第三列包含相应的 map 值。 C.txt的样本如下所示
0 0 5, 0 1 5, 0 2 1, 0 3 8, 0 4 11, ..., ...
注意
我有 400000 个文件来执行此操作,因此速度很重要。我为此编写了一个程序,但运行速度很慢。如果不是创建新文件 (C.txt) 替换可以节省时间,那么该解决方案也是可以接受的。
while read line
do
origPhoneme=`echo $line| cut -d " " -f3`
while read mapLine
do
mapPhone=`echo $mapLine | cut -d " " -f1`
replacementPhone=`echo $mapLine | cut -d " " -f2`
if [ $mapPhone == $origPhoneme ]
then
echo $replacementPhone >> checkFile
break
fi
done < B.txt
done< A.txt
paste -d ""A.txt checkFile > C.txt
通过使用此代码,C.txt 文件包含我不想要的 A.txt 的第三列
最佳答案
Python(或 shell 脚本)应该足够快 - 您的任务主要受 I/O 速度限制,而不是处理速度。
所以我建议使用这样的 Python 方法:
将B.txt
读入字典中进行快速查找:
with open("B.txt") as file:
B = dict(line.strip().split() for line in file)
然后处理A.txt
,创建C.txt
:
with open("A.txt") as infile, open("C.txt", "w") as outfile:
for line in infile:
start, end = line.strip().rsplit(None, 1)
outfile.write("{0} {1}\n".format(start, B[end]))
关于python - 如何用 shell 脚本中另一个文件的值替换文件中字段(列)的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407323/