0

I learn AWK not long a go and still confused. I try using AWK to compare two txt files and generate a merged output based on the compare results.

file1.txt

budi
andi

file2.txt

sinta Sep 29 17:12
andi Sep 15 17:12
kuro Sep 9 17:12
budi Sep 2 17:13

I try using

awk 'FNR==NR{a[$1];next};$NF in a' cobafull.txt coba.txt > result.txt`

Here is the result

budi
andi

Output I want like this

budi Sep 2 17:13
andi Sep 15 17:12

Please need your advice. Thank you.

sorry add noted that

file1.txt = coba.txt
file2.txt = cobafull.txt
3
  • 2
    Sounds like you just need to reverse the order of the files in the awk argument list. Also, if you're still learning awk it might be best to make the code more clear and explicit so that you can see what's going on rather than using one-liners that have already been through a round of "code golf".
    – DopeGhoti
    Oct 13, 2020 at 17:18
  • 1
    $NF is the last field, so it is testing for 17:13, not for budi. That would be $1. Oct 13, 2020 at 17:31
  • @DopeGhoti usually I find the code from googling thats why in one-liners, Thank you for your suggestion
    – Ario
    Oct 14, 2020 at 5:29

2 Answers 2

2

If file file1.txt is accepted as coba.txt and file2.txt as cobafull.txt than:

awk 'NR == FNR {A[$1]=$0; next}; {print A[$0]}' coba{full,}.txt

output:

budi Sep 2 17:13
andi Sep 15 17:12

If the order of the output is not important:

awk 'A[$1]++' coba{,full}.txt

output:

andi Sep 15 17:12
budi Sep 2 17:13
0
-1

Presuming that by file1.txt and file2.txt you meant coba.txt and cobafull.txt respectively, and that the latter is the "wider" file, then when you do this:

awk 'FNR==NR{a[$1];next};$NF in a' cobafull.txt coba.txt > result.txt

then what is happening is you are reading in first the "full" file. When it reads in the first line, awk sees this record:

sinta Sep 29 17:12

It then sets a["sinta"] equal to "siinta", and stops processing the record. It then reads in the rest of the file, accordingly.

Then, it starts reading the second file. It reads the first line, and sees this record:

sinta

and then checks to see whether the index "sinta" exists in the array a. It does, and so it prints the record, which at this points is simply:

sinta

If you swtich the order of the files in the argument list, it will work as you presumably expect it to.

0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .