34

I have a file with two columns as

1 1
2 3
3 4

and a file with one column as

6
7
9

I would like to add the second file in the first one. The output should be:

1 1 6
2 3 7
3 4 9
Valerio D. Ciotti
  • 1,369
  • 2
  • 17
  • 27

3 Answers3

47
$ pr -mts' ' file1 file2
1 1 6
2 3 7
3 4 9

$ paste -d' ' file1 file2
1 1 6
2 3 7
3 4 9
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
11
awk 'NR==FNR{a[NR]=$0;next}{print a[FNR],$0}' file1 file2

Note: Will work with files of same length. If file lengths' are different, go with sudo_O's solution.


Just for the heck of it, here is an awk command that I think should simulate paste. Purely for fun though, if I were you I would still go with sudo_O's solution (or may be not!)

awk 'NR==FNR{a[++y]=$0;next}{b[++x]=$0}
END{z=x>y?x:y;while(++i<=z){print a[i],b[i]}}' file1 file2
Community
  • 1
  • 1
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
  • 2
    Pretty cool answer. Would you mind explaining how it works? I don't get why it's `a[NR]` first and then `a[FNR]`. – abalter Mar 27 '17 at 19:56
  • Or just print the result instead of building up the `b` array. Assuming the both file has the same size. But this solution is more general. – TrueY Feb 04 '23 at 17:50
3

A pure solution can be:

echo -e "1 1\n2 3\n3 4" >onefile
echo -e "6\n7\n9" >twofile

exec 3<twofile
while read x; do read -u 3 y; echo $x $y; done <onefile
# exec 3<&- # Close the file, if not needed

or on a more general way:

exec {fd}<twofile
while read x; do read -u $fd y; echo $x $y; done <onefile
# exec $fd<&- # Close the file, if not needed

Output:

1 1 6
2 3 7
3 4 9
TrueY
  • 7,360
  • 1
  • 41
  • 46