Nested loop for reading two files with bash

Viewed 1203

I'm currently trying to use the following code to merge two input files:

for i in `cat $file1`; do
    for j in `cat $file2`; do
        printf "%s %s\n" "$i" "$j"
    done
done

Given files created as follows:

printf '%s\n' A B C >file1
printf '%s\n' 1 2 3 >file2

...my expected/desired output is:

A 1
B 2
C 3

But instead, the output I'm getting is:

A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
C 3

How can this be fixed?

2 Answers

Possible by using the pr command from coreutils, also possible with other commands/tools like paste and also by Shell and AWK scripts. Least effort by using the commands from coreutils as only a few parameters are required on the commandline, like in this example:

pr -TmJS" " file1 file2

where:

  • -T turns off pagination
  • -mJ merge files, Joining full lines
  • -S" " separate the columns with a blank

The following command will work:

paste -d' ' file1 file2

The paste coreutils utility merges files line by line. The -d options is used to specify the delimeter, ie. space here.

Related