, , , , , ,

The problem: I have  two files, file-1 and file-2, each of which has two columns; and I want to add the second column of the second file as the third column in the first file.
Let’s say the following is the content of file-1:

A   1
B   2
C   3

and that of file-2:

D   4
E   5
F   6

and I want to have something like this in file-3

A   1   4
B   2   5
C   3   6

Of course, the actual data are not as simple as the above!


$ awk '{str1=$1; str2=$2; getline < "file-2"; print str1" \t "str2" \t "$2 > "file-3"}' file-1

I inserted the tab characters (\t) just to make file-3 look nice (scientists don’t care about white spaces, do they?)!

Reference: here.


UPDATE: As reader ‘boul oumag’ pointed out, an alternative to this is to use the command line utility ‘paste’.    It concatenates each pair of lines — the corresponding ones from each file — and prints it out in the standard output. There is no option to choose which columns to merge. However, you can always redirect the output to a file, open it with vim and reorder/delete columns using vim’s visual block mode (use control+V).