You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:55:23