2013-01-24 22 views
0

我有两个输入文件,即:shell脚本 - 从文件拷贝行者皆

file1 
123 
456 
789 

file2 
123|foo 
456|bar 
999|baz 

我需要从文件2,它的键是file1中的行复制,所以最终的结果是:

file3 
123|foo 
456|bar 

现在,我使用的是通过他们的密钥文件循环和使用grep的为每一个shell脚本:

grep "^${keys[$keyindex]}|" $datafile >&4 

但你可以IMA gine,这是非常缓慢的。密钥文件(file1)大约有400,000个密钥,数据文件(file2)大约有750,000行。有一个更好的方法吗?

+0

你为什么使用shell脚本? – gahooa

+0

在更大的脚本中,在这一点之前发生了很多其他步骤。我希望不需要保持两件不同的事情。 – Greg

+0

我从来没有尝试过它,但我认为你可以将python代码嵌入到多行bash字符串中,并直接将它发送给python解释器而不需要单独的文件。 – gahooa

回答

4

您可以尝试使用join

join -t'|' file1.txt file2.txt > file3.txt 
+0

+1非常好,假设这两个文件都被排序。 – kojiro

+0

工作,谢谢! – Greg

0

我会使用类似的Python,如果使用优化的数据类型一样set这将处理它相当快。不确定你的具体要求,所以你需要做相应的调整。

#!/usr/bin/python 

# Create a set to store all of the items in file1 
Set1 = set() 
for line in open('file1', 'r'): 
    Set1.add(line.strip()) 

# Open a file to write to 
file4 = open('file4', 'w') 

# Loop over file2, and only write out the items found in Set1 
for line in open('file2', 'r'): 
    if '|' not in line: 
     continue 

    parts = line.strip().split('|', 1) 
    if parts[0] in Set1: 
     file4.write(parts[1] + "\n") 
0

join是最好的解决方案,如果排序是好的。 awk解决方案:

awk -F \| ' 
    FILENAME==ARGV[1] {key[$1];next} 
    $1 in key 
' file1 file2