Search code examples
bashfor-loopnested-loopsimaging

Nested for loop in bash, where the code performs a different action for each item in the loop


I have 10 directories (MDD1, MDD2, MDD3, MDD4, MDD5, OCD1, OCD2, OCD3, OCD4, OCD5), and each directory has an image (lesion_right_warped.nii.gz). I'm trying to write a code that will multiply each image by a pre-specified value {88,-8.7,-33.3,0,20,-43,4,-7,27,82} - i.e. multiply MDD1/lesion_right_warped.nii.gz by 88, MDD2/lesion_right_warped.nii.gz by -8.7, etc. My below code doesn't work properly, because it eventually just ends up multiplying all the images by 82 (it loops through each value and overwrites the previous).

#!/bin/bash
for i in *;    
do
    for j in {88,-8.7,-33.3,0,20,-43,4,-7,27,82}; 
    do
          fslmaths $i/lesion_right_warped.nii.gz -mul $j $i/lesion_right_response.nii.gz
    done
done

Any advice would be greatly appreciated! Thank you!


Solution

  • You could prepare two arrays and then use a shared index:

    dirs=(*)
    factors=(88 -8.7 -33.3 0 20 -43 4 -7 27 82)
    
    # Make sure both have the same number of elements
    ((${#dirs[@]} != ${#factors[@]})) && exit 1
    
    for ((i = 0; i < ${#dirs[@]}; ++i)); do
        fslmaths "${dirs[i]}/lesion_right_warped.nii.gz" \
            -mul "${factors[i]}" "${dirs[i]}/lesion_right_response.nii.gz"
    done