字符串检索 各种系统

字符串检索 各种系统

目录

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_only=False): """搜索文件内容""" 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', encoding=encoding, errors='ignore') 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', default=r'E:\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', action='store_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"