文件名的成对组合

rmf*_*rmf 6 bash

例如,如果我在一个目录中有 n 个文件;

a
b
c
Run Code Online (Sandbox Code Playgroud)

如何将这些文件的成对组合(非定向)传递给函数?

预期的输出是

a-b
a-c
b-c
Run Code Online (Sandbox Code Playgroud)

以便它可以传递给像这样的函数

fn -file1 a -file2 b
fn -file1 a -file2 c
...
Run Code Online (Sandbox Code Playgroud)

这就是我现在正在尝试的。

for i in *.txt
 do
  for j in *.txt
   do
    if [ "$i" != "$j" ]
     then
      echo "Pairs $i and $j"
     fi
   done
 done
Run Code Online (Sandbox Code Playgroud)

输出

Pairs a.txt and b.txt
Pairs a.txt and c.txt
Pairs b.txt and a.txt
Pairs b.txt and c.txt
Pairs c.txt and a.txt
Pairs c.txt and b.txt
Run Code Online (Sandbox Code Playgroud)

我仍然有重复项(ab 与 ba 相同),我想也许有更好的方法来做到这一点。

ilk*_*chu 8

将文件名放在一个数组中,并通过两个循环手动运行它。

如果j < i其中ij分别是外循环和内循环中使用的索引,则每个配对仅获得一次。

$ 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
Run Code Online (Sandbox Code Playgroud)


Ste*_*ris 5

您的脚本非常接近,但您想删除重复项;即 ab 被视为 ba 的重复项。

我们可以使用不等式来处理这个问题;仅当第一个文件按字母顺序位于第二个文件之前时才显示文件名。这将确保每场比赛只有一场。

for i in *.txt
do
  for j in *.txt
  do
    if [ "$i" \< "$j" ]
    then
     echo "Pairs $i and $j"
    fi
  done
done
Run Code Online (Sandbox Code Playgroud)

这给出了输出

Pairs a.txt and b.txt
Pairs a.txt and c.txt
Pairs b.txt and c.txt
Run Code Online (Sandbox Code Playgroud)

这不是一个有效的算法(它是 O(n^2)),但可能足以满足您的需求。