【问题标题】:How to iterate through a bash list and get all possible combinations of 2 elements?如何遍历 bash 列表并获得 2 个元素的所有可能组合?
【发布时间】:2017-10-12 21:25:18
【问题描述】:

我有一个问题。我有一个包含许多文件的文件夹,我需要对我的文件中的 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

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

for i in [0,N]
  for j in [i,N]
    #the combination would be i,j

我的文件列表如下所示:

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

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

提前感谢您的帮助!

【问题讨论】:

  • 是的,for 循环可以嵌套。只要确保每个人都有一个结束do/done。如果这还不足以帮助您,那么您没有告诉您的文件有些问题。更新您的 Q 以包含一小组文件名并显示您希望它们如何组合。祝你好运。
  • (顺便说一句,你的问题不是很准确,但你应该avoid parsing ls)。

标签: bash shell


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2010-10-02
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多