Grep and Python(Grep 和 Python)
问题描述
我需要一种通过 Unix 命令行中的正则表达式使用 grep 搜索文件的方法.例如,当我在命令行中输入:
I need a way of searching a file using grep via a regular expression from the Unix command line. For example when I type in the command line:
python pythonfile.py 'RE' 'file-to-be-searched'
我需要在文件中搜索正则表达式 'RE'
并打印出匹配的行.
I need the regular expression 'RE'
to be searched in the file and print out the matching lines.
这是我的代码:
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'
但是当我输入一个不存在的单词时,找不到匹配项
不会打印
But when I enter a word which isn't present, no matches found
doesn't print
推荐答案
自然的问题是为什么不直接使用 grep?!但假设你不能......
The natural question is why not just use grep?! But assuming you can't...
import re
import sys
file = open(sys.argv[2], "r")
for line in file:
if re.search(sys.argv[1], line):
print line,
注意事项:
search
而不是match
来查找字符串中的任意位置- 逗号 (
,
) 后print
删除回车(行将有一个) argv
包含python文件名,所以变量需要从1开始
search
instead ofmatch
to find anywhere in string- comma (
,
) afterprint
removes carriage return (line will have one) argv
includes python file name, so variables need to start at 1
这不处理多个参数(像 grep 那样)或扩展通配符(像 Unix shell 那样).如果你想要这个功能,你可以使用以下方法获得它:
This doesn't handle multiple arguments (like grep does) or expand wildcards (like the Unix shell would). If you wanted this functionality you could get it using the following:
import re
import sys
import glob
for arg in sys.argv[2:]:
for file in glob.iglob(arg):
for line in open(file, 'r'):
if re.search(sys.argv[1], line):
print line,
这篇关于Grep 和 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!