按目录分支/叶子分组文件

时间:2011-04-06 13:47:34

标签: bash shell find

我是bash的新手,处理目录树结构时遇到了困难。 我有一个目录结构如下

I/A/dataA.dat
I/B/dataB.dat
I/C/dataC.dat

II/A/dataA.dat
II/B/dataB.dat
II/C/dataC.dat

III/A/dataA.dat
III/B/dataB.dat
III/C/dataC.dat

我现在想要I/A/dataA.dat处理I/B/dataB.datII/A/dataA.dat处理II/B/dataB.dat等(针对每种情况)。但我不想处理I/A/dataA.datII/B/dataB.dat

查找此类文件对的最佳方法是什么?

我希望将找到的对的名称传递给bash函数,如下所示

function process_pair()
{
  fileOne=$1; #for example II/A/data.dat
  fileTwo=$2; #for example II/B/data.dat
  //the rest of the function that processes this pair.
}

但我不知道如何获取变量$1$2

我目前正在使用bash并从dirs=find $SOURCE -type d -links 2命令开始(找到所有叶子目录 - adapted from this question)。然后我尝试循环这些(使用substring命令获取上面的目录)。 但是,我发现这很困难,我认为必须有更好的方法。

1 个答案:

答案 0 :(得分:1)

在shell中轻松完成:

for dir in I II III; do
    subdirs=()
    for subdir in $dir/*; do subdirs+=("${subdir##*/}"); done
    for (( i=0 ;i<${#subdirs[*]}-1; i++ ));  do
        for (( j=i ;j<${#subdirs[*]} ;j++ ));  do
            a=${subdirs[$i]}
            b=${subdirs[$j]}
            process_pair $dir/$a/data$a.dat $dir/$b/data$b.dat
        done
    done
done