如何编写Shell脚本实现基于正则列表的子目录匹配搜索?
问题描述
我想写一个Shell脚本,遍历results.txt里的每一条正则表达式,在子目录中搜索匹配项。想问下用find命令是不是合适的方案?我也可以试试Python,但相关经验不足。
results.txt里的正则表达式示例:/underway/(.)*.(GPS|gps)
我目前写的代码片段:
for i in results.txt find -regextype egrep -regex "i" if find: Print ("Found") else: print ("not found")
解答
find命令完全适合这个场景——它本身就是专门用来遍历目录搜索文件的工具,搭配正则表达式匹配正好契合你的需求。
先给你修正并完善Shell脚本:
#!/bin/bash # 遍历results.txt中的每一行正则表达式 while IFS= read -r regex; do # 跳过空行 [[ -z "$regex" ]] && continue # 使用find搜索,屏蔽权限不足等无关错误信息 matches=$(find . -regextype egrep -regex "$regex" 2>/dev/null) if [[ -n "$matches" ]]; then echo "正则表达式 '$regex' 找到匹配项:" echo "$matches" else echo "正则表达式 '$regex' 未找到匹配项" fi done < results.txt
关键修正点:
- 用
while read循环代替for in:for in会把文件内容按空格分割,while read能正确读取每一行正则表达式,避免正则里的空格导致拆分错误 IFS= read -r:保留行首/行尾的空格,防止正则表达式被意外修改2>/dev/null:屏蔽find可能输出的权限不足等无关错误信息- 用变量存储搜索结果,通过判断变量是否为空来输出对应提示,逻辑更清晰
如果实在想尝试Python,这里给个新手友好的简单版本:
import os import re # 读取正则表达式文件,跳过空行 with open('results.txt', 'r') as f: regex_list = [line.strip() for line in f if line.strip()] # 遍历当前目录下所有子目录和文件 for root, dirs, files in os.walk('.'): for file in files: full_path = os.path.join(root, file) # 逐个正则匹配 for regex in regex_list: if re.fullmatch(regex, full_path): print(f"正则表达式 '{regex}' 找到匹配文件:{full_path}") break # 如果需要匹配目录,加上这段 for dir_name in dirs: full_dir_path = os.path.join(root, dir_name) for regex in regex_list: if re.fullmatch(regex, full_dir_path): print(f"正则表达式 '{regex}' 找到匹配目录:{full_dir_path}") break
Python版本说明:
os.walk('.')自动遍历当前目录下所有层级的子目录和文件re.fullmatch实现和find的-regex一致的完全匹配逻辑(如果需要部分匹配,换成re.search即可)- 先把所有正则表达式读取到列表,再逐个匹配每个文件/目录的完整路径,逻辑直观易懂
内容的提问来源于stack exchange,提问作者ruribe
相关产品推荐
相关产品推荐

