• Uncategorized

About linux : Nested-bash-loop-to-execute-only-once

Question Detail

I need to create multiple file having content like this below and substitute value for this from other different 3 files.


I tried to add values to the above content using while loop but it executed with 3^3 combination ,actually what i need is that to create a file with first line of the 3 files substituted and second file with 2nd line of the 3 files substituted and so on.

This is the code i used.

while read line1;
 while read line2;
 while read line3;
 echo "
 name: $line1
 url:  $line2
 description: $line3

" > $line1.txt ;

done < url.txt
done < description.txt
done < name.txt

Question Answer

In a nested loop, each loop will process the whole file in one go, resulting in out-of-sync output.

Instead you need to read the 3 files in a single while loop, using extra file descriptors to process the other files:

while read name && read description <&3 && read url <&4; do
  echo "
  name: $name
  url:  $url
  description: $description

  " > $name.txt
done < name.txt 3< description.txt 4< url.txt

Assuming the files name.txt, url.txt, and description.txt have the same number of lines, this task could be done using paste and sed utilities:

paste -d '\n' name.txt url.txt description.txt |
sed 'N;N;s/\(.*\n\)\(.*\n\)/name: \1url: \2description: /'

or, if files are not too large, an alternative bash solution could be:


mapfile names < name.txt
mapfile urls < url.txt
mapfile descs < description.txt

for ((i = 0; i < ${#names[@]}; ++i)); do
    printf 'name: %surl: %sdescription: %s' \
           "${names[i]}" "${urls[i]}" "${descs[i]}"

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.