尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

字符串检索 各种系统

字符串检索 各种系统 目录python检索windows cmd检索字符串返回文件名和包含字符串的行linux系统python检索# !/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import argparse from pathlib import Path def search_files(root_dir, search_pattern, extensions, exclude_dirs, show_filename_onlyFalse): 搜索文件内容 regex re.compile(search_pattern, re.IGNORECASE) results [] for root, dirs, files in os.walk(root_dir): # 排除目录 if exclude_dirs: dirs[:] [d for d in dirs if d not in exclude_dirs] for file in files: if not any(file.endswith(ext) for ext in extensions): continue file_path os.path.join(root, file) # 尝试多种编码 for encoding in [utf-8, utf-16-le, utf-16-be, gbk, gb2312]: try: with open(file_path, r, encodingencoding, errorsignore) as f: lines f.readlines() matches [] for line_num, line in enumerate(lines, 1): if regex.search(line): matches.append((line_num, line.rstrip())) if matches: results.append((file_path, matches)) if show_filename_only: print(file_path) else: print(f\n {file_path}) for line_num, line in matches: # 高亮匹配部分可选 highlighted regex.sub(lambda m: f\033[1;31m{m.group(0)}\033[0m, line) print(f {line_num}: {highlighted}) break except: continue return results def main(): parser argparse.ArgumentParser(description在代码文件中搜索文本) parser.add_argument(--pattern,default修复, help搜索关键词支持正则) parser.add_argument(-d, --dir, defaultrE:\pro_math\BambuStudio, help搜索目录默认当前目录) parser.add_argument(-e, --ext, nargs, default[.cpp, .h, .c, .hpp, .cc, .po, .json], help文件扩展名如 .cpp .h) parser.add_argument(-x, --exclude, nargs, default[deps, build, .git, __pycache__], help排除的目录) parser.add_argument(-l, --files-only, actionstore_true, help只显示文件名不显示匹配行) args parser.parse_args() print(f 搜索: {args.pattern}) print(f 目录: {args.dir}) print(f 扩展名: {, .join(args.ext)}) print(f 排除: {, .join(args.exclude)}) print( * 80) results search_files(args.dir, args.pattern, args.ext, args.exclude, args.files_only) print(f\n✅ 找到 {len(results)} 个匹配文件) if __name__ __main__: main()windows cmd检索字符串返回文件名findstr /s /i /m Non-manifold *.cpp返回文件名和包含字符串的行findstr /s /i /n Netfabb *.cpp字符串检索linux系统grep -ril Non-manifold --include*.cpp
返回列表