CyberKeeda In Social Media

BASH : While Loop with Multiple Variables from multiple file as input



This blog post will help you to use the WHILE loop with multiple variables fetched out from multiple files.
If you have two files and some content within it which you want in parallel to work together.

Lets assume , i have a two file named as  hostname.txt and serial_no.txt and here are the contents for it.

cybeerkeeda@Linux-Maniac:~ cat hostname.txt 
Myhost01
Myhost02
Myhost03

cybeerkeeda@Linux-Maniac:~ cat serial_no.txt 
SGH120X
SGH345U
SGH6YUI


Now what I want my output should look like 

Myhost01    SGH120X
Myhost02    SGH345U
Myhost03    SHH6YUI

We can do these in numbers of way but for now we will simply demonstarate, how we can use WHILE loop to achieve it.

while read -r x && read -r y <&3; do echo " $x  $y " ; done<hostname.txt 3<serial_no.txt

We can even write it to a file too

while read -r x && read -r y <&3; do echo " $x  $y " ; done<hostname.txt 3<serial_no.txt  >> /tmp/my_inventory.txt


Depending upon your need you can modify the commands , just one more example , i have used the same loop to modify some data with SED.

while read -r x && read -r y <&3; do   echo "sed -n '/6\/$x\/2016/,/6\/$y\/2016/p'"; done <old_date.txt 3<new_date.txt > sed_date.txt






















No comments:

Post a Comment

Designed By Jackuna