import subprocess
output = subprocess.check_output(["/usr/bin/env", "grep", "-nHr", "hello", "."])
matches = (line.split(":", 2) for line in output.split("\n") if line != "")
for [file, line, text] in matches:
....
>>> from glob import glob
>>> key = 'hello'
>>> for file in glob("e:\data\*.txt"):
with open(file,'r') as f:
line_no = 0
for lines in f:
line_no+=1
if key.lower() in lines.lower():
print "Found in " + file + "(" + str(line_no) + "): " + lines.rstrip()
Found in e:\data\data1.txt(1): Hello how are you
Found in e:\data\data2.txt(4): Searching for hello
Found in e:\data\data2.txt(6): 3 hello
这将找到所有提到“你好”在当前目录或下面。
man grep
获取有关选项的详细信息。请注意,您将需要引用任何特殊字符;如果您要查找简单的单词,这是不必要的,但是如果您处理的是用户输入,则需要关心它。在使用glob作为替代,您可以筛选特定的文件名、扩展名或目录中的所有文件。在
相关问题 更多 >
编程相关推荐