*NIX Tricks

[awk] Add another column from a second file

Posted in awk, bash, csh, linux, osx, unix by kousik on October 24, 2009

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!

Solution:

$ 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.

Tagged with: , , , , ,

2 Responses

Subscribe to comments with RSS.

  1. Alex said, on March 24, 2011 at 4:37 AM

    Thanks a lot! The result is perfect. I`ve searched this solution for a long time.

  2. Thanks
    On solaris10 I had to do it with gawk
    gawk ‘{str1=$0; getline “file-3″}’ file-1


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.