0

I have file1 which has 3 columns and file2 which has 8 columns. What I wanted to do was if the first 3 columns in file 2 were found in file 1, then print out the entire 8 columns in file 2.

I have tried codes like

awk 'NR==FNR{c[$1$2$3]++;next};c[$1$2$3]>0' file1 file2

...but it only printed out the last matching line in file2.

I have no idea what was wrong. Could anyone help me out? I'd really appreciate it! Thank you in advance!

file1 looks like this

7000000185249020    89812   89911
7000000185249020    89912   90011
7000000185249020    202532  202631
7000000185249020    202632  202704
7000000185249020    202764  202863
.....

file2 looks like this

7000000185249020    89812   89911   100 14.1    20  0.511   48
7000000185249020    89912   90011   100 12.7    19.8    0.642   49
7000000185249020    90012   90023   12  11  17.9    0.704   58.3
  • Are the two files the same length in lines? If so you could use paste to merge them and then check for $1==$5 && $2 == $6 [etc]. – DopeGhoti Apr 18 '18 at 21:56
  • @DopeGhoti the two files are not same length in lines. file 2 actually has more lines than file 1 – Jing Apr 18 '18 at 22:00
  • In that case, if either file is longer than the other, all of the nonmatching lines at the end will be thrown out. – DopeGhoti Apr 18 '18 at 22:01
  • I would like to keep all the matching lines. I don't why the command I used printed out only the last matching line but not the others.. – Jing Apr 18 '18 at 22:03
  • I believe because next skips the rest of the awk script for the purposes of the current record. – DopeGhoti Apr 18 '18 at 22:17
0

If the two files are the same length, you can do this:

paste file1 file2 | awk '$1==$4 && $2==$5 && $3==$6 { print $4,$5,$6,$7,$8,$9,$10,$11}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.