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?

2

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

In 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".
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.

3 Comments

Thank you so much !!!! It works . Do you know if there is any alternative way to get the same result with a loop ?
@KamilCuk, ...consider the usual chiding about answering an obvious duplicate to have taken place.
@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<file1 4<file2 suggested as an answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.