4

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?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
elias
  • 53
  • 5
  • Sorry for that. I just editted my question. – elias Jun 11 '19 at 13:13
  • 1
    And btw: grab good reads: [Why you don't read lines with "for"](https://mywiki.wooledge.org/DontReadLinesWithFor) and [How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?](https://mywiki.wooledge.org/BashFAQ/001) – KamilCuk Jun 11 '19 at 13:18

2 Answers2

2

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
ennox
  • 206
  • 1
  • 5
  • In [How to Answer](https://stackoverflow.com/help/how-to-answer), note the section "Answer Well-Asked Questions", and the bullet point therein regarding questions which "have been asked and answered many times before". – Charles Duffy Jun 11 '19 at 13:32
1

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.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • Thank you so much !!!! It works . Do you know if there is any alternative way to get the same result with a loop ? – elias Jun 11 '19 at 13:27
  • @KamilCuk, ...consider the usual chiding about answering an obvious duplicate to have taken place. – Charles Duffy Jun 11 '19 at 13:31
  • @elias, follow the "already has an answer here" links at the top of the question; you'll see many of the existing instances of this question have something like `while IFS= read -r line1 <&3 && IFS= read -r line2 <&4; do echo "Read $line1 from file-1 and $line2 from file-2"; done 3 – Charles Duffy Jun 11 '19 at 13:33