2

I have a file strings.txt containing 100 strings, each on a line

string1
string2
...
string100

For each of those strings, I want to find all the lines in file_to_look.txt that contain that string. Now, I could run grep 100 times like grep string1 file_to_look.txt, then grep string2 file_to_look.txt, etc., but that would take a lot of typing time for me.

Is there a way that I don't have to do so much typing?

EDIT: Solutions that go through file_to_look.txt only 1 time instead of 100 times would be great, since my file_to_look.txt is quite large.

5 Answers 5

4

-f is for passing (GNU) grep a pattern file.

grep -f strings.txt file_to_look.txt
Sign up to request clarification or add additional context in comments.

3 Comments

This seems like the most elegant way to do it; +1
Does it go through the input file 1 time or 100 times?
It reads the pattern file once, then scans the input file once, so just 1 time.
0

Usually xargs is used for repeating commands with multiple values:

xargs -I{} grep {} file_to_look.txt < strings.txt

Comments

0

You can do it using while read, like this:

cat strings.txt | while read line ; do grep "$line" file_to_look.txt ; done

For more alternative ways take a look at:

Comments

0
while read line; do grep "$line" file_to_look.txt; done < strings.txt

That does exactly what you asked for. Substitute ";" for newlines as you see fit.

xargs is the other option people will suggest. My suggestion is to generally look for another alternative first, as xarg has a bunch of gotchas which can make things go very wrong.

Greg's bash wiki on xargs

Comments

0

You can do it with the following short script:

#!/bin/bash

file_name=string.txt
file_to_look=file_to_look.txt
patterns=$(tr '\n' '|' $filename)
patterns=${patterns%?} # remove the last |
grep -E $patterns $file_to_look

This rounds up all of your search patterns together and hands it off to grep in one go with the -E option, so grep only has to parse through file_to_look.txt once, instead of a 100 times.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.