使用python从另一个文件中的一个文件中grep行

时间:2012-05-08 01:30:35

标签: python grep

在python中替换“grep”的类似问题;但这里的复杂性是grepped来自另一个文件的变量(行)。我无法弄清楚如何使用像re.findall()

这样的函数来做到这一点

文件1:

1  20  200
1  30  300

file2的:

1  20  200  0.1  0.5
1  20  200  0.3  0.1
1  30  300  0.2  0.6
1  40  400  0.9  0.6
2  50  300  0.5  0.7

file1中的每一行都是我的模式;我需要从file2中搜索这样的模式。 那么结果应该是:

    1  20  200  0.1  0.5
    1  20  200  0.3  0.1
    1  30  300  0.2  0.6

我一直在尝试使用bash或python解决问题,但无法弄清楚。 THX

4 个答案:

答案 0 :(得分:4)

这是一个基于非正则表达式的解决方案:

with open('/tmp/file1') as f:
  lines1 = f.readlines()

with open('/tmp/file2') as f:
  for line in f:
    if any(line.startswith(x.strip()) for x in lines1):
      print line,

答案 1 :(得分:1)

您可以利用正则表达式中的|字符表示匹配左侧图案或右侧图案的事实:

import re

with open('file1') as file1:
    patterns = "|".join(re.escape(line.rstrip()) for line in file1)

regexp = re.compile(patterns)
with open('file2') as file2:
    for line in file2:
        if regexp.search(line):
            print line.rstrip()

当我在您的示例文件上尝试此操作时,它会输出:

1   20  200 0.1 0.5
1   20  200 0.3 0.1
1   30  300 0.2 0.6

顺便说一句,如果你想在bash中解决这个问题,下面应该这样做:

grep -f file1 file2 

答案 2 :(得分:0)

我认为你需要自己的循环

file1patterns = [ re.Pattern(l) for l in f1.readlines() ]
lineToMatch = 0
matchedLines = []
for line in f2.readlines():
  if file1patterns[lineToMatch].matches(line):
    matchedLines += line
    lineToMatch += 1
  else:
    lineToMatch = 0
    matchedLines = []
  if len(matchedLines) == len(file1patterns)
    print matchedLines
    lineToMatch = 0
    matchedLines = []

(不是实际编译Python,但希望足以让你继续前进)

答案 3 :(得分:0)

步骤1:读入文件1中的所有行,拆分它们并将它们作为元组添加到集合中。这将有助于我们在下一步中更快地进行查找。

with open('file1', 'r') as f:
    file1_lines = set([tuple(line.strip().split()) for line in f])

步骤2:从file2过滤符合您标准的行,即如果它们以file1中的任何行开头:

with open('file2', 'r') as f2:
    for line in itertools.ifilter(lambda x: tuple(x.split()[:3]) in file1_lines, f2):
        print line
相关问题