Question

Let's say I have queries.txt.

queries.txt:

cat
dog
123

now I want to use them are queries to find lines in myDocument.txt using grep.

cat queries.txt | xargs grep -f myDocument.txt

myDocument has lines like

cat
i have a dog
123
mouse

it should return the first 3 lines. but it's not. instead, grep tries to find them as file names. what am i doing wrong?

Was it helpful?

Solution

Here, you just need:

grep -f queries.txt myDocument.txt

This causes grep to read the regular expressions from the file queries.txt and then apply them to myDocument.txt.

In the xargs version, you were effectively writing:

grep -f myDocument.txt cat dog 123

If you absolutely must use xargs, then you'll need to write:

xargs -I % grep -e % myDocument.txt < queries.txt

This avoids a UUOC — Useless Use of cat – award by redirecting standard input from queries.txt. It uses the -I % option to specify where the replacement text should go in the command line. Using the -e option means that if the pattern is, say --help, you won't run into problems with (GNU) grep treating that as an argument (and therefore printing its help message).

OTHER TIPS

The grep -e option will take a pattern string as an argument. -f treats the argument as a file name of a file with patterns in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top