Combine multiple files using awk

March 10, 2010 at 09:02:14
Specs: Windows XP
Can anyone help me to compare two files and combine them using awk in shell script?
File1 Data
010010003 RED
010010013 BLUE
010010055 GREEN
010010059 RED

File2 Data
010010013 360 200 50
010010055 290 206 55
010010059 210 206 60
010010025 204 70 100
I need to compare the two file: for the same color, if the first number in file1 is the same with the first number in file2, create file 3 , eg.
010010003 360 200 50 RED
010010059 210 206 60 RED
I have a series of inputs for different months, so I want to use bash or csh script to deal with this. Since I have lots of other variables need to set, like
set DATA1 = $file1
set DATA2 = $file2
I don’t know much about awk, please HELP!
Thank you.

See More: Combine multiple files using awk

Report •

March 10, 2010 at 14:06:54
Your spec is not totally clear. You state if the line number in File1 agrees with the corresponding column in File2 to print. Your data doesn't agree with that.

This is the 4th line of File1:

010010059 RED

And this is the 3rd line of File2:

010010059 210 206 60

It's not the 4th line so it's not going the way I am interpreting your spec. Please clear that up and I might be able to help you.

Report •

March 10, 2010 at 18:17:12
Thank you so much for reply. Yes, there is a mistake.

Here is what I want:

For RED (same for all other color)
where I see 010010013 in file1 and 010010013 in file2 create file3 which looks like this:
010010013 360 200 50 RED
same for site 010010059, will be printed into file3 with format as belo
010010059 210 206 60 RED

Is this clear? Thank uuuuu...

Report •

March 11, 2010 at 22:35:28
One way is to read the first file into an array. The index into the array is field1 and the the color is the data. I then loop thru the second file sampling the first field and if it exists, print out the line per spec.

This assumes that the first field in file1 is unique:


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

} ' file2data

Report •

Related Solutions

March 15, 2010 at 07:08:08
It is working, thank you so much!

Report •

Ask Question