bash - Looping over two variables in tandem (ie. over pairs) in shell -


this question has answer here:

i have list of files in ids1. example

s1_aaa s1_aab s1_aac 

i want submit jobs these files using sbatch: use

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

this works fine.

now try 2 variables in loop. example have file ids2

s2_aaa s2_aab s2_aac 

i want submit jobs files in ids1 , ids2 simultaneously i.e. pairs (s1_aaa,s2_aaa), (s1_aab,s2_aab), (s1_aac,s2_aac) , on. when try

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

i error

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

what doing wrong?

read each array:

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

...or, in bash 3.x:

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

...and iterate on indexes:

for idx in "${!ids1[@]}"; # iterate on indexes in ids1   id1=${ids1[$idx]} # , use index items in *both* arrays   id2=${ids2[$idx]}   echo "processing $id1 , $id2" done 

another option use paste combine both files single stream, , use bashfaq #1 while read loop iterate on 2 combined columns:

while ifs=$'\t' read -r id1 id2;   echo "processing $id1 , $id2" done < <(paste ids1 ids2) 

Comments