【问题标题】:Using bash to iterate through similarly named files and grep使用 bash 遍历类似命名的文件和 grep
【发布时间】:2020-05-23 16:07:57
【问题描述】:

我有一个基本文件列表:

file1.txt 
file2.txt 
file3.txt 

和目标文件列表:

target1.txt
target2.txt 
target3.txt

我想使用 bash 通过循环执行以下命令:

grep -wf "file1.txt" "target1.txt" > "result1.txt" 
grep -wf "file2.txt" "target2.txt" > "result2.txt" 

除了最后一个整数之外,文件都将具有相同的名称,它将是一个系列 (1:22)。

【问题讨论】:

    标签: bash grep


    【解决方案1】:

    使用 for 循环:

    for((i=1; i<=22; i++)); do
      grep -wf "file$i.txt" "target$i.txt" > "result$i.txt" 
    done
    

    【讨论】:

      【解决方案2】:

      任意数量的file#.txttarget#.txt

      #!/usr/bin/env bash
      
      shopt -s extglob # Enable extended globbing patterns
      
      # Iterate all file#.txt
      for f in file+([[:digit:]]).txt; do
        # Extract the index from the file name by stripping-out all non digit characters
        i="${f//[^[:digit:]]//}"
      
        file="$f"
        target="target$i.txt"
        result="result$i.txt"
      
        # If both file#.txt and target#.txt exists
        if [ -e "$file" ] && [ -e "$target" ]; then
          grep -wf "$file" "$target" >"$result"
        fi
      done
      

      【讨论】:

        【解决方案3】:

        这是一个单行版本,适合带大括号扩展的命令行:

        for i in {1..22};do grep -wf "file$i.txt" "target$i.txt" > "result$i.txt"; done
        

        【讨论】:

          【解决方案4】:

          使用 GNU Parallel 并行执行所有操作:

           parallel 'grep -wf file{}.txt target{}.txt > result{}.txt' ::: {1..22}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2011-01-10
            • 2013-09-20
            • 2011-12-29
            • 2019-03-08
            • 1970-01-01
            • 2017-01-01
            • 1970-01-01
            相关资源
            最近更新 更多