1

I'm trying to retrieve the the matching lines from a file, however the file that has the "index" or list of matches to retrieve also has duplicate entries and I want to print out the duplicates as well.

Example:

File 1 (index file or list of strings to match)

abc
tgf
abc
ggg
aaa
fff

File 2 (what I want to retrieve for each of the matches in file 1)

Fred   1   3   abc
Amy    2   4   ggg
Dan    5   6   tgf
Mike   9   1   fff
Steve  2   1   aaa

My desired result would be (order is not important, just that I match every line):

Fred   1   3   abc
Dan    5   6   tgf
Fred   1   3   abc
Amy    2   4   ggg
Steve  2   1   aaa
Mike   9   1   fff

I'm familiar and have tried grep as follows, but it does not print the duplicate entries.

grep -Fwf file1.txt file2.txt

Fred   1   3   abc
Amy    2   4   ggg
Dan    5   6   tgf
Mike   9   1   fff
Steve  2   1   aaa
6

Via awk

awk 'NR==FNR{A[$4]=$0;next}{print A[$1]}' file2.txt file1.txt

Or sorted output via join:

join -o 2.1 2.2 2.3 2.4 -2 4 <(sort file1.txt) <(sort -k4 file2.txt)

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.