LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   awk: compare fields of file 1 to fields of file 2 (https://www.linuxquestions.org/questions/linux-newbie-8/awk-compare-fields-of-file-1-to-fields-of-file-2-a-4175578714/)

beca123456 04-30-2016 05:48 PM

awk: compare fields of file 1 to fields of file 2
 
Hi,


Using awk, I am trying to append the comment(s) of file2 at the end of file1 if:
- field1 of file1 is equal to field1 of file2
AND
- field2 of file1 is ≥ field2 of file2 and ≤ field3 in file2

file1.tab (NF is constant):
Code:

1  20  value1
4  73  value2

file2.tab (NF is variable):
Code:

1  10  30  commentA1  commentA2
2  50  89  commentB1
4  55  90  commentC1

output:
Code:

1  20  value1  commentA1  commentA2
4  73  value2  commentC1

I can (kind of) output the first condition (i.e. if $1 file1 = $2 file2), but don't see how to do deal with the second condition:
Code:

gawk 'BEGIN{FS="\t"}NR==FNR{a[$1]=$0; next}{print $0 FS a[$1]}' file2 file1
which produces:
Code:

1  20  value1  1  10  30  commentA1  commentA2
4  73  value2  4  55  90  commentC1


syg00 04-30-2016 08:03 PM

First you'd better get your head around the first condition. You aren't testing for equality of anything, let alone $1. Also, saving into the array like that will replace (i.e. lose) previous records if $1 in file2 is not unique. And once saved, field-splitting on the saved data is no longer in effect.
Take it one step at a time.

grail 05-01-2016 03:28 AM

The other issue I see is that file2 seems to be able to have a variable number of comments and as these are the only things you need to keep, you need a way to append all but the first 3 fields.

As syg00 has said, you need to take this one step at a time. I would ignore file1 for the time being and work out how to store all the required information from file2.


All times are GMT -5. The time now is 06:24 AM.