先贴完整代码,功能描述见代码中的备注
运行命令:python grep.py D:\linux-master touch脚本名为:grep.py参数1:文件夹路径(D:\linux-master)参数2:要检索的关键字(touch)
import os
import re
import sys
def find_files(path
, names
):
for root
,dirs
,files
in os
.walk
(path
):
for file in files
:
name
= os
.path
.join
(root
,file)
names
.append
(name
)
def search_word(path
, word
):
lnum
= 1
global total
file = open(path
, 'r', encoding
='UTF-8', errors
='ignore')
for line
in file.readlines
():
if word
in line
:
print('total:%d' % total
)
print("File: " + path
)
print("Line: %d" % lnum
+ line
)
total
= total
+ 1
lnum
= lnum
+ 1
dire
= sys
.argv
[1]
word
= sys
.argv
[2]
paths
= []
total
= 0
find_files
(dire
, paths
)
leng
= len(paths
)
for i
in range(leng
):
search_word
(paths
[i
], word
)
我这里运行的结果是:
total:5339
File: D:\linux-master\drivers\watchdog\wdt.c
Line: 566 * will not touch PC memory so all is fine. You just have to load a new
total:5340
File: D:\linux-master\drivers\xen\gntalloc.c
Line: 323 /* Once we finish add_grefs, it is unsafe to touch the new reference,
total:5341
File: D:\linux-master\drivers\xen\gntdev.c
Line: 1016 * Since this vma's mappings can't be touched without the
total:5342
File: D:\linux-master\drivers\xen\gntdev.c
Line: 1048 * enough to not touch it until the mmap() call
以上,描述不好,请见谅