使用 bash 脚本将另一个脚本应用于目录中的每个文件,如矩阵

Using a bash script to apply another script to every file in a directory like a matrix

假设我的目录中有五个文件。

文件:1、2、3、4 和 5

我有一个脚本可以执行数学过程来比较两个文件,我想在目录中的每个文件上使用这个脚本,示例如下。

将文件 1 与 2、3、4 和 5 进行比较

将文件 2 与 3,4, & 5 进行比较

将文件 3 与文件 4 和 5 进行比较

比较文件 4 和 5

文件遵循此命名方案 filename_V0001.txt

如何编写一个简单的 bash 脚本来执行此操作?

for a in *
do
  start=0
  for b in *
  do
    if [ "$start" = 1 ]
    then
      echo "Comparing $a with $b ..."
      diff "$a" "$b"
    elif [ "$a" = "$b" ]
    then
      start=1
    fi
  done
done

当然可以在 glob 模式中给出文件的任何命名方案,例如。 G。 for a in filename_V*.txt.

script_v1.sh:

#!/bin/bash
compare="/path/to/my/compare_tool"

for i in {1..5}; do
    for j in $(seq $((i+1)) 5); do
        echo "Comparing $i and $j"
        compare filename_V000$i.txt filename_V000$j.txt > result_$i_$j.txt
    done
done

result_v1:

$ > bash script_v1.sh
Comparing 1 and 2
Comparing 1 and 3
Comparing 1 and 4
Comparing 1 and 5
Comparing 2 and 3
Comparing 2 and 4
Comparing 2 and 5
Comparing 3 and 4
Comparing 3 and 5
Comparing 4 and 5
$ >

script_v2.sh:

#!/bin/bash
compare="/path/to/my/compare_tool"

for i in {1..100}; do
    for j in $(seq $((i+1)) 100); do
        fi="Filename_V$(printf "%04d" $i).txt"
        fj="Filename_V$(printf "%04d" $j).txt"
        if [[ -f "$fi" && -f "$fj" ]]; then
            echo "Comparing $fi and $fj"
            compare "$fi" "$fj" > result_$i_$j.txt
        fi
    done
done

result_v2:

$ > bash script_v2.sh
Comparing Filename_V0001.txt and Filename_V0002.txt
...
Comparing Filename_V0001.txt and Filename_V0100.txt
Comparing Filename_V0002.txt and Filename_V0003.txt
...
Comparing Filename_V0002.txt and Filename_V0100.txt
Comparing Filename_V0003.txt and Filename_V0004.txt
...
Comparing Filename_V0099.txt and Filename_V0100.txt
$ >

ASSUMPTIONS:

  • the scripts are called from the path the files reside in

一个相当通用的方法:

#!/bin/sh
for comp1; do
  shift
  for comp2; do
    echo "Comparing '$comp1' with '$comp2'"
    do_compare "$comp1" "$comp2"
  done
done

然后您可以使用要比较的文件列表调用该脚本:

do_all_compares Filename_V*.txt

for x等同于for x in "$@"。该列表是在执行 for 语句时计算的,因此在循环开始时发生的 shift 只会影响内部比较的列表。