Friday, October 7, 2022

[SOLVED] How to echo the same elements locations from several lists

Issue

I have 3 different lists:

Names.txt:

Adam

Josh

Ben

Ages.txt:

18

14

19

Pets.txt:

Dog

Cat

Fish

And i need to build a script in bash to echo the next output:

My name is Adam and my age is 18 and i have a Dog

My name is Josh and my age is 14 and i have a Cat

My name is Ben and my age is 19 and i have a Fish

I need to print all the elements on tge same location in the lists within the same output


Solution

Use paste to combine the files

There is the little known paste command. It merges the content of multiple files line for line. So the first part would be

paste Names.txt Ages.txt Pets.txt

Which gives:

Adam    18      Dog
Josh    14      Cat
Ben     19      Fish

Then you use your usual shell tooling to read over that. If you can use awk it would be:

paste Names.txt Ages.txt Pets.txt | awk '{printf("My name is %s and my age is %d and I have a %s\n",$1, $2, $3);}'

If you cannot use awk, a while read loop with a printf command can be used. Again we pipe the paste output into the command:

paste Names.txt Ages.txt Pets.txt | while read name age pet
do
   printf "My name is %s and my age is %d and I have a %s\n" $name $age $pet
done

Here the read name age pet reads each line of paste output and assigns the three words in each line to the three variables name, age and pet which are then used as arguments for the printf command. The while loop executes the printf command as long as read is able to read lines, i.e. the loop stops printing after three lines.



Answered By - Lars Fischer
Answer Checked By - Mildred Charles (WPSolving Admin)