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

时间:2015-06-08 21:47:54

标签: bash shell matrix scripting file-handling

让我们在我的目录中说我有五个文件。

档案:1,2,3,4,& 5

我有一个脚本会进行数学处理来比较两个文件,我想在目录中的每个文件上使用这个脚本,例如下面的例子。

比较文件1到2,3,4,& 5

比较文件2到3,4,& 5

比较文件3到4& 5

比较文件4到5

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

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

3 个答案:

答案 0 :(得分:1)

<强> 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
$ >
  

假设:

     
      
  • 从文件所在的路径调用脚本
  •   

答案 1 :(得分:0)

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

答案 2 :(得分:0)

一种相当普遍的做法:

#!/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只会影响内部比较的列表。