1

I have fileA and fileB.

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

fileA:

QW123
BH876
PR009

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.

web
  • 193

1 Answers1

3

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:

steeldriver
  • 81,074
  • 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 04 '20 at 17:51
  • 1
    @web yes it is - for example $2 in a {print > $2 ".output"} – steeldriver Nov 04 '20 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 05 '20 at 04: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. – steeldriver Nov 05 '20 at 12:14