Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a column from a file to another file

Tags:

bash

awk

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 
like image 475
Valerio D. Ciotti Avatar asked Jun 13 '13 19:06

Valerio D. Ciotti


People also ask

How do I add a column to a file in Linux?

For reference, paste -d' ' file1 file2 will paste file2 to file 1 (as an appended column) with a space as a delimiter; paste -d'\t' file1 file2 will paste with a tab as a delimiter. E.g. paste -d'\t' file1. tsv file2.

How do I select a column in a file?

ALT + Left Mouse Click puts you in Column Mode Select. It's quite an useful shortcut that may help you. This is by far the simplest solution.


2 Answers

$ 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 
like image 110
Chris Seymour Avatar answered Oct 12 '22 11:10

Chris Seymour


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 
like image 28
jaypal singh Avatar answered Oct 12 '22 10:10

jaypal singh