对两个变量进行串联循环(例如:在壳中



在ids1中有一个文件列表。示例

s1_aaa
s1_aab
s1_aac

我想使用sbatch为这些文件提交作业:我使用

for x in `cat ids1`;do sbatch batch_job.sbatch $x ;done 

现在我在for循环中尝试2个变量。我有另一个文件ids2,比如

s2_aaa
s2_aab
s2_aac

我想同时为ids1ids2中的文件提交作业,即对(s1_aaa,s2_aaa), (s1_aab,s2_aab), (s1_aac,s2_aac)等。当我尝试

for x,y in `cat ids1;cat ids2`;do sbatch batchjob.sbatch $x $y ;done

我得到错误

-bash: `x,y': not a valid identifier

我做错了什么?

读入数组:

# in bash 4.0 or newer
readarray -t ids1 <ids1 # read each line from file ids1 into array ids1
readarray -t ids2 <ids2 # read each line from file ids2 into array ids2

…或者,在bash 3.x中:

ids1=( ); ids2=( )
while IFS= read -r id; do ids1+=( "$id" ); done <ids1
while IFS= read -r id; do ids2+=( "$id" ); done <ids2

…并遍历索引:

for idx in "${!ids1[@]}"; do # iterate over indexes in ids1
  id1=${ids1[$idx]} # and use that index to look up items in *both* arrays
  id2=${ids2[$idx]}
  echo "Processing $id1 and $id2"
done

另一种选择是使用paste将两个文件组合成一个流,并使用BashFAQ #1 while read循环遍历两个组合的列:

while IFS=$'t' read -r id1 id2; do
  echo "Processing $id1 and $id2"
done < <(paste ids1 ids2)

如果两个文件中的行匹配,您可以先粘贴它们,然后对它们进行成对迭代,即

while read a b; do sbatch batchjob.sbatch $a $b; done < <(paste ids1 ids2)

相关内容

最新更新