e271p314 e271p314 - 1 year ago 328
Linux Question

How to run grep inside awk?

Suppose I have a file

with few columns and few rows, the first column is the key, and a directory
with files which contain some of these keys. I want to find all lines in the files in
which contain these key words. At first I tried to run the command

cat input.txt | awk '{print $1}' | xargs grep dir

This doesn't work because it thinks the keys are paths on my file system. Next I tried something like

cat input.txt | awk '{system("grep -rn dir $1")}'

But this didn't work either, eventually I have to admit that even this doesn't work

cat input.txt | awk '{system("echo $1")}'

After I tried to use
to escape the white space and the
sign, I came here to ask for your advice, any ideas?

Of course I can do something like

for x in `cat input.txt` ; do grep -rn $x dir ; done

This is not good enough, because it takes two commands, but I want only one. This also shows why
doesn't work, the parameter is not the last argument


Try following

awk '{print $1}' input.txt | xargs -n 1 -I pattern grep -rn pattern dir