Search code examples
bashloopsnested

how to loop through a nested loop so that the main loop and the nested one can go in parallel


I have two text files, one with patient IDs (subjects.txt) and one with some measures(number_of_slices.txt). Both text files contain 1 column only.

In a third file (.xmlg), I have put specific words (e.g.,number_of_brain_slices) that I want to be automatically substituted for the 1st patients ID with the 1st measure, then the 2nd patients ID and the second measure. However, with the current loop, I am producing these .xmlg files with a different patient_ID but with the same measure (the number of slices) as I don't know how to write the nested loop and make it increase by 1 position every time, so patient and measure go in parallel - second patient - second measure, third patient - third measure etc. Does anyone know how to do that in bash?

#!bin/bash

for sub in `cat subjects.txt`
do 
    for f in `cat number_of_slices.txt`
    do 
    sed -i "s/number_of_brain_slices/${f}/g" \
           /data/mri_measures/analysis/set_files/${sub}.xmlg;
    done
done


Solution

  • A suggestion using the paste command:

    #! /bin/sh
    
    set -o nounset
    
    WorkDir='/data/mri_measures/analysis/set_files'
    
    paste subjects.txt number_of_slices.txt \
    | while read -r ID Measure
      do    File="${WorkDir}/${ID}.xmlg"
            if test -f "$File"
               then sed -i "s/number_of_brain_slices/${Measure}/g" "$File"
            else echo "missing xmlg file for subject \"$ID\"!"
            fi
      done
    

    paste file1 file2 will merge the two files line-wise.

    Hope that helps.