python实现类似linux grep命令

    技术2022-07-16  77

    先贴完整代码,功能描述见代码中的备注
    运行命令:python grep.py D:\linux-master touch脚本名为:grep.py参数1:文件夹路径(D:\linux-master)参数2:要检索的关键字(touch) import os import re import sys # 遍历当前路径下所有的文件路径,并保存到names里面 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

    以上,描述不好,请见谅

    Processed: 0.012, SQL: 9