Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read content from two files and merge into a 3rd file in bash shell

How do you read/process 2 files in sync with each other in bash?

I have 2 text files which have the same number of lines/items in them. One file is

a
b
c

The other file is

1
2
3

How do I loop through these files in sync so that a is associated with 1, b->2, c->3?

I thought that I could read in the files as an array and then process them with an index but it seems like my syntax/logic is incorrect.

So doing f1=$(cat file1) makes f1 = a b c. I thought doing f1=($(cat file1)) would make it into an array but it makes f1=a and thus no array for me to process.

In case anyone was wondering what my messed up code is:

hostnames=($(cat $host_file))  
# trying to read in as an array, which apparently is incorrect
roles=($(cat $role_file))

for i in {0..3}
do
   echo ${hostnames[$i]}   
   # wanted to iterate through each element in the file/array
   # but there is only one object instead of N objects
   echo ${roles[$i]}
done
like image 884
Classified Avatar asked Jun 21 '13 19:06

Classified


1 Answers

You can use file descriptors:

while read -r var_from_file1 && read -r var_from_file2 <&3; do 
    echo "$var_from_file1 ---> $var_from_file2"
done <file1 3<file2

Output:

a ---> 1
b ---> 2
c ---> 3
like image 113
jaypal singh Avatar answered Sep 28 '22 09:09

jaypal singh