Reputation: 1449
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
Upvotes: 34
Views: 75422
Reputation: 7610
A pure bash 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
Upvotes: 3
Reputation: 77105
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
Upvotes: 12
Reputation: 85795
$ 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
Upvotes: 50