我需要一种使用 grep 通过 Unix 命令行中的正则表达式搜索文件的方法。例如,当我在命令行中键入:
python pythonfile.py 'RE' 'file-to-be-searched'
我需要在文件中搜索正则表达式 'RE'
并打印出匹配的行。
我的密码是这样的:
import re
import sys
search_term = sys.argv[1]
f = sys.argv[2]
for line in open(f, 'r'):
if re.search(search_term, line):
print line,
if line == None:
print 'no matches found'
但是当我输入一个不存在的单词时,no matches found
不会打印