如何遍历bash列表并获得2个元素的所有可能组合? [英] How to iterate through a bash list and get all possible combinations of 2 elements?
问题描述
我有一个问题.我有一个包含许多文件的文件夹,我需要对文件中2个文件的所有组合执行一个程序.
I have an issue. I have a folder with many files and i need to execute a program on all combinations of 2 files among my files.
到目前为止,我的linux bash脚本看起来像这样:
My linux bash script looks like this so far:
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的新手,在其他语言中,它类似于:
I'm new to bash, in other languages this would look something like:
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
ex_10.1 ex_10.2 ex_10.3 ex_10.4 ex_10.5
我想在其中的2个文件的所有组合上执行python程序(所以我执行了10次程序)
And i want to execute a python program on all combinations of 2 files among these (so i execute my program 10 times)
预先感谢您的帮助!
推荐答案
如果我们使用数组并按索引进行迭代,则您描述的逻辑很容易被转录:
The logic you describe is easily transcribed if we use an array, and iterate by index:
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
(以不允许恶意文件名或错误将额外条目注入数组的方式),我们希望用类似于以下内容的逻辑替换该初始分配行:
To safely implement sort -V
(in a manner that doesn't allow malicious filenames or bugs to inject extra entries into the array), we'd want to replace that initial assignment line with logic akin to:
files=( )
while IFS= read -r -d '' file; do
files+=( "$file" )
done < <(printf '%s\0' * | sort -V -z)
...使用NUL分隔符(与换行符不同,在UNIX文件名中不能以原义形式存在)分隔流中与 sort
之间的名称.
...which uses NUL delimiters (which, unlike newlines, cannot exist as a literal in UNIX filenames) to separate names in the stream to and from sort
.
这篇关于如何遍历bash列表并获得2个元素的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!