Grep和Python [英] Grep and Python
问题描述
我需要一种通过Unix命令行的正则表达式使用grep搜索文件的方法。例如,当我输入命令行时:
python pythonfile.py'RE''要搜索的文件'
我需要正则表达式'RE'
在文件中搜索并打印出匹配的行。
以下是我的代码:
import re
import sys
search_term = sys.argv [1]
f = sys.argv [2]
$ b $ (f,'r'):
如果re.search(search_term,line):
print line,
if line == None:
print'没有找到匹配'
但是当我输入一个不存在的单词时,找不到匹配
不打印
自然的问题是为什么不只是使用grep? !但假设你不能... ...
pre $ code $ import $ $ $ $
$ b = open(sys.argv [2],r)
用于文件中的行:
如果re.search(sys.argv [1],line):
打印行,
注意事项: 这不处理多个参数(如grep)或扩展通配符(如Unix shell)。如果你想要这个功能,你可以使用下面的代码: 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: I need the regular expression Here's the code I have: But when I enter a word which isn't present, The natural question is why not just use grep?! But assuming you can't... Things to note: 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:
这篇关于Grep和Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
搜索
而不是匹配
可在字符串中找到任何位置$ b $ print
之后的b ,
)移除回车(行将有一个)
argv
包含python文件名,因此变量需要从1开始
import re
import sys
import在glob.iglob(arg)中为sys.argv [2:]:
中的arg创建了glob
:
用于打开(文件,'r')行:
:
if re.search(sys.argv [1],line):
print line,
python pythonfile.py 'RE' 'file-to-be-searched'
'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'
no matches found
doesn't printimport re
import sys
file = open(sys.argv[2], "r")
for line in file:
if re.search(sys.argv[1], line):
print line,
search
instead of match
to find anywhere in string,
) after print
removes carriage return (line will have one)argv
includes python file name, so variables need to start at 1import 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,