【发布时间】:2012-01-26 12:29:41
【问题描述】:
有一个文件 (query.txt),其中包含一些要使用 grep 与其他文件匹配的关键字/短语。以下代码的最后三行运行良好,但是当在 while 循环中使用相同的命令时,它会进入无限循环或其他东西(即没有响应)。
import os
f=open('query.txt','r')
b=f.readline()
while b:
cmd='grep %s my2.txt'%b #my2 is the file in which we are looking for b
os.system(cmd)
b=f.readline()
f.close()
a='He is'
cmd='grep %s my2.txt'%a
os.system(cmd)
【问题讨论】:
-
既然 Python 中有
re模块,为什么还要使用grep? -
这是一个作业。我们被告知你使用 grep :(
-
如果您的搜索模式中有空格,您需要在构建的命令行中使用引号,就像在测试的最后 3 行中一样。您希望命令读取:
grep "He is" my2.txt但就目前而言,命令行是:grep He is my2.txt