Awk help, using 2 files

November 16, 2010 at 14:40:26
Specs: Unix

I have two text files: file1, file2. I would like to create a third file, file3, that contains the first column of file1 and the second column of file2. The columns are separated by spaces. For example,

1 4 6 0
5 4 7 6

a k l
k u r

So my output should be:

1 a
5 k

How would I do this using Awk? Thanks in advance!

See More: Awk help, using 2 files

November 16, 2010 at 17:14:27
If you want the 2nd column of file2, shouldn't the output be:

1 k
5 u

Anyway, read file1 into an array and do something like this:


awk ' BEGIN {
   while ( getline < "file1data" > 0 )
if(NR in myarr)
   printf("%s %s\n", myarr[NR], $2)

} ' file2data

Report •

November 17, 2010 at 07:17:26
Thanks for the quick response....Just curious, what does the statement

if(NR in myarr)


Report •

November 17, 2010 at 08:55:58
NR is awk's ordinal number of the current record - the current line as awk reads thru the file.

if(NR in myarr) is a conditional that asks if the index - NR in this case - exists in the array, myarr. If it does print out the line.

For this solution, it's probably not need since the number of lines in each file are the same. Awk's arrays are associative. One of the side effects of associative arrays is that the act of accessing an array element creates it.

I hope this makes sense.

Report •
Related Solutions

Ask Question