Awk help, using 2 files

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

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,

file1
1 4 6 0
5 4 7 6

file2
a k l
k u r

So my output should be:

file3
1 a
5 k

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


See More: Awk help, using 2 files

Report •

#1
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:

#!/bin/ksh

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

} ' file2data


Report •

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

if(NR in myarr)

mean?


Report •

#3
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