Pairwise combinations of filenames

Put the file names in an array and run through it manually with two loops.

You get each pairing only once if if j < i where i and j are the indexes used in the outer and the inner loop, respectively.

$ touch a b c d
$ f=(*)
$ for ((i = 0; i < ${#f[@]}; i++)); do 
      for ((j = i + 1; j < ${#f[@]}; j++)); do 
          echo "${f[i]} - ${f[j]}"; 
      done;
  done 
a - b
a - c
a - d
b - c
b - d
c - d

You're very close in your script, but you want to remove duplicates; i.e a-b is considered a duplicate of b-a.

We can use an inequality to handle this; only display the filename if the first file comes before the second file alphabetically. This will ensure only one of each matches.

for i in *.txt
do
  for j in *.txt
  do
    if [ "$i" \< "$j" ]
    then
     echo "Pairs $i and $j"
    fi
  done
done

This gives the output

Pairs a.txt and b.txt
Pairs a.txt and c.txt
Pairs b.txt and c.txt

This isn't an efficient algorithm (it's O(n^2)) but may be good enough for your needs.

Tags:

Bash