I have fileA and fileB.

fileA is storing a list of names I wanted to extract from the second column of fileB.




MJ194   PR009   100
PR009   IJ940   78
JG948   BH448   58

desire output:

MJ194   PR009   100
JG948   BH448   58

I am trying it with the command below but none of them worked. Wondering what is left out in between the codes.

  • for i in $(cat fileA); do awk '$2=="$i"' fileB; done
  • for i in $(cat fileA); do awk -v 'i="$i"' '$2=="i"' fileB; done

Any help would be much appreciated.

1 Answer 1


Your second attempt would "work" if you remove extraneous quoting:

for i in $(cat fileA); do awk -v i="$i" '$2==i' fileB; done    # but don't do this

However, if you are determined to use a shell loop, it would be better to use while:

while IFS= read -r i; do awk -v i="$i" '$2==i' fileB; done < fileA    # don't do this either

Better would be to avoid the shell loop altogether:

awk 'NR==FNR{a[$1]; next} $2 in a' fileA fileB

See also:

  • Hi @steeldriver, thanks! The third options looked pretty neat. But wondering if it possible to print output files according to fileA strings? I used to do >> $i.output with for loops to get the output files (where >> $i.output will generate QW123.output; BH876.output and PR009.output).
    – web
    Nov 4, 2020 at 17:51
  • 1
    @web yes it is - for example $2 in a {print > $2 ".output"} Nov 4, 2020 at 17:59
  • Thanks! Do you have any recommended open resources or reference book (probably) that I can learn more on writing codes as in the third option?
    – web
    Nov 5, 2020 at 4:50
  • 1
    @web I usually reach for The GNU Awk User’s Guide - just be aware that not all gawk features are supported by other awk implementations. Nov 5, 2020 at 12:14

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.