Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take two at a time in a bash "for file in $list" construct

Tags:

bash

for-loop

I have a list of files where two subsequent ones always belong together. I would like a for loop extract two files out of this list per iteration, and then work on these two files at a time (for an example, let's say I want to just concatenate, i.e. cat the two files).

In a simple case, my list of files is this:

FILES="file1_mateA.txt file1_mateB.txt file2_mateA.txt file2_mateB.txt"

I could hack around it and say

FILES="file1 file2"
for file in $FILES
do
    actual_mateA=${file}_mateA.txt
    actual_mateB=${file}_mateB.txt

    cat $actual_mateA $actual_mateB
done

But I would like to be able to handle lists where mate A and mate B have arbitrary names, e.g.:

FILES="first_file_first_mate.txt first_file_second_mate.txt file2_mate1.txt file2_mate2.txt"

Is there a way to extract two values out of $FILES per iteration?

like image 581
Alexander Engelhardt Avatar asked Jan 21 '14 11:01

Alexander Engelhardt


1 Answers

Use an array for the list:

files=(fileA1 fileA2 fileB1 fileB2)
for (( i=0; i<${#files[@]} ; i+=2 )) ; do
    echo "${files[i]}" "${files[i+1]}"
done
like image 179
choroba Avatar answered Oct 07 '22 20:10

choroba