如何遍历 bash 列表并获得 2 个元素的所有可能组合?

Rou*_*cha 2 bash shell

我有一个问题。我有一个包含许多文件的文件夹,我需要对我的文件中 2 个文件的所有组合执行一个程序。

到目前为止,我的 linux bash 脚本如下所示:

for ex in $(ls ${ex_folder}/${testset_folder} | sort -V ); do
   #ex is the name of my current file
   #I would like to do something like a nested loop where
   # ex2 goes from ex to the end of the list $(ls ${ex_folder}/${testset_folder} | sort -V )
done
Run Code Online (Sandbox Code Playgroud)

我是 bash 新手,在其他语言中,这看起来像:

for i in [0,N]
  for j in [i,N]
    #the combination would be i,j
Run Code Online (Sandbox Code Playgroud)

我的文件列表如下所示:

ex_10.1 ex_10.2 ex_10.3 ex_10.4 ex_10.5

我想对其中 2 个文件的所有组合执行一个 python 程序(所以我执行我的程序 10 次)

预先感谢您的帮助!

Cha*_*ffy 6

如果我们使用数组并按索引迭代,您描述的逻辑很容易转录:

files=( * )                                       # Assign your list of files to an array
max=${#files[@]}                                  # Take the length of that array

for ((idxA=0; idxA<max; idxA++)); do              # iterate idxA from 0 to length
  for ((idxB=idxA; idxB<max; idxB++)); do         # iterate idxB from idxA to length
    echo "A: ${files[$idxA]}; B: ${files[$idxB]}" # Do whatever you're here for.
  done
done
Run Code Online (Sandbox Code Playgroud)

为了安全地实现sort -V(以不允许恶意文件名或错误将额外条目注入数组的方式),我们希望用类似于以下的逻辑替换初始赋值行:

files=( )
while IFS= read -r -d '' file; do
  files+=( "$file" )
done < <(printf '%s\0' * | sort -V -z)
Run Code Online (Sandbox Code Playgroud)

...它使用 NUL 分隔符(与换行符不同,它不能作为 UNIX 文件名中的文字存在)将流中的名称与sort.