user1497773
user1497773

Reputation: 1

Looping and merging 2 files

First of all, please pardon me, I am a noob. My problem is as follows:

I have 2 text files - file1 and file2. Following are the file samples and the desired output:

file1:

A B C
D E F
G H I

file2:

a1 a2 a3
b1 b2 b3
c1 c2 c3

Desired output:

A B C a1 a2 a3
A B C b1 b2 b3
A B C c1 c2 c3
D E F a1 a2 a3
D E F b1 b2 b3
D E F c1 c2 c3

and so on.

Can anybody please help me out with this?

Upvotes: 0

Views: 110

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 359955

awk 'FNR == NR {file2[FNR] = $0; c++; next} {for (i = 1; i <= c; i++) {print $0, file2[i]}}' file2 file1

Read all the lines of file2 into an array. For each line of file1, loop through the array and print the line from file1 and the line from file2.

In Bash:

while read -r line
do
    file2+=("$line")
done < file2

while read -r line
do
    for line2 in "${file2[@]}"
    do
        echo "$line $line2"
    done
done < file1

Upvotes: 2

Related Questions