Bash Shell脚本-按键从文件复制行

Bash Shell脚本-按键从文件复制行,bash,shell,grep,Bash,Shell,Grep,我有两个输入文件,以便: file1 123 456 789 file2 123|foo 456|bar 999|baz 我需要从文件2中复制键位于文件1中的行,因此最终结果是: file3 123|foo 456|bar 现在,我正在使用一个shell脚本,它循环遍历密钥文件,并对每个密钥文件使用grep: grep "^${keys[$keyindex]}|" $datafile >&4 但是你可以想象,这是非常缓慢的。密钥文件(file1)约有400000个密钥,数据

我有两个输入文件,以便:

file1
123
456
789

file2
123|foo
456|bar
999|baz
我需要从文件2中复制键位于文件1中的行,因此最终结果是:

file3
123|foo
456|bar
现在,我正在使用一个shell脚本,它循环遍历密钥文件,并对每个密钥文件使用grep:

grep "^${keys[$keyindex]}|" $datafile >&4
但是你可以想象,这是非常缓慢的。密钥文件(file1)约有400000个密钥,数据文件(file2)约有750000行。有更好的方法吗?

您可以尝试使用:

您可以尝试使用:


我会使用类似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")

我会使用类似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")

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

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

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

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

为什么要使用shell脚本?在更大的脚本中,在此之前还有许多其他步骤。我希望不需要维护两种不同的东西。我从未尝试过,但我认为可以将python代码嵌入到多行bash字符串中,直接发送到python解释器,而不需要单独的文件。为什么要使用shell脚本?在更大的脚本中,在此之前还有很多其他步骤。我希望不需要维护两种不同的东西。我从未尝试过,但我认为可以将python代码嵌入到多行bash字符串中,直接发送到python解释器,而不需要单独的文件。