Home > database >  Nested bash loop to execute only once
Nested bash loop to execute only once

Time:12-31

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

 name: 
 url:  
 description: 

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;
 do 
 while read line2;
 do 
 while read line3;
 do 
 echo "
 name: $line1
 url:  $line2
 description: $line3

" > $line1.txt ;

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

CodePudding user response:

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

CodePudding user response:

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:

#!/bin/bash

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]}"
done
  • Related