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.

Mika H.
  • 4,119
  • 11
  • 44
  • 60

5 Answers5

4

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

grep -f strings.txt file_to_look.txt
j.w.r
  • 4,136
  • 2
  • 27
  • 29
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

Ian Kelling
  • 9,643
  • 9
  • 35
  • 39
0

Usually xargs is used for repeating commands with multiple values:

xargs -I{} grep {} file_to_look.txt < strings.txt
BeniBela
  • 16,412
  • 4
  • 45
  • 52
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:

Community
  • 1
  • 1
Nelson
  • 49,283
  • 8
  • 68
  • 81
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.

sampson-chen
  • 45,805
  • 12
  • 84
  • 81