如何用shell脚本中的另一个文件中的值替换文件中字段(列)的特定值?

时间:2013-12-05 18:00:30

标签: python shell

我有两个文件说A.txt和B.txt。 A.txt有三列,如下所示

0 0 17
0 1 17
0 2 4
0 3 50
0 4 90 
....
.... 

我必须将第三列值替换为相应的地图值,这些地图值保存在B.txt中,如下所示

1 1
2 1
3 1
4 1
..
17 5
..
50 8
..
90 11
..

B.txt中第一列的值和A.txt中第三列的值是相同的,我需要创建一个新文件(比如C.txt),其前两列与之相同A.txt但第三列包含相应的地图值。 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&gt; C.txt

通过使用此代码,C.txt文件包含我不想要的第三列A.txt

1 个答案:

答案 0 :(得分:4)

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]))