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

编写Bash脚本:遍历指定文件夹并将grep结果导出为.res文件

我帮你补全并优化了这个Bash脚本,完全满足你的需求——遍历指定文件夹、筛选特定扩展名文件、用grep批量检索并保存结果。下面是完整的脚本和详细说明:

完整实现脚本
#!/bin/bash

# Default values
directory=$(pwd)
searchterms="searchterms.txt"
extension=".end"

usage() {
    echo "usage: fmat [[[-f file ] [-d directory ] [-e ext]] | [-h]]"
    echo " file - text file containing a return-delimited list of search terms"
    echo " directory - directory to process (default: current working directory)"
    echo " ext - file extension of files to process (default: .end)"
    echo ""
}

# Parse command line arguments
while getopts ":f:d:e:h" opt; do
    case ${opt} in
        f )
            searchterms=$OPTARG
            ;;
        d )
            directory=$OPTARG
            ;;
        e )
            extension=$OPTARG
            # Ensure extension starts with a dot if not provided
            [[ $extension != .* ]] && extension=".$extension"
            ;;
        h )
            usage
            exit 0
            ;;
        \? )
            echo "Invalid option: -$OPTARG" 1>&2
            usage
            exit 1
            ;;
        : )
            echo "Option -$OPTARG requires an argument." 1>&2
            usage
            exit 1
            ;;
    esac
done
shift $((OPTIND -1))

# Validate search terms file exists
if [[ ! -f "$searchterms" ]]; then
    echo "Error: Search terms file '$searchterms' does not exist." 1>&2
    exit 1
fi

# Validate directory exists
if [[ ! -d "$directory" ]]; then
    echo "Error: Directory '$directory' does not exist." 1>&2
    exit 1
fi

# Core logic: iterate over files with specified extension, run grep, save results
echo "Processing files in $directory with extension $extension..."
for file in "$directory"/*"$extension"; do
    # Skip if no matching files exist (avoids literal *extension being processed)
    [[ -f "$file" ]] || continue

    # Define output file name (replace extension with .res, or append .res if no extension)
    output_file="${file%$extension}.res"

    # Run grep with terms from searchterms.txt, save to output file
    grep -f "$searchterms" "$file" > "$output_file"

    # Optional: Print status message
    echo "Saved results for $file to $output_file"
done

echo "Processing complete!"

关键功能说明

1. 灵活的参数配置

脚本支持通过命令行参数自定义:

  • -f:指定存储搜索词的文本文件(每行一个搜索词)
  • -d:指定要遍历的目标目录(默认当前工作目录)
  • -e:指定要处理的文件扩展名(默认.end,如果输入不带点会自动补全,比如输入txt会变成.txt)
  • -h:显示帮助信息

2. 输入有效性检查

脚本会提前验证:

  • 搜索词文件是否存在
  • 目标目录是否存在
    如果任一条件不满足,会立即输出错误提示并退出,避免后续执行出现意外问题。

3. 核心检索逻辑

  • 用for循环遍历目标目录下所有符合指定扩展名的文件
  • 处理“无匹配文件”的边界情况(防止把*.end当作文件名处理)
  • 自动生成输出文件名:将原文件的指定扩展名替换为.res
  • 使用grep -f批量读取搜索词文件中的内容,执行检索并将结果写入对应.res文件

使用示例

  • 使用默认参数运行:
./fmat.sh
  • 指定自定义搜索词文件、目标目录和扩展名:
./fmat.sh -f my_search_terms.txt -d /home/user/documents -e md
  • 查看帮助信息:
./fmat.sh -h

内容的提问来源于stack exchange,提问作者Dycey

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:48:06