user3255841
user3255841

Reputation: 113

Grep multiple strings from text file

Okay so I have a textfile containing multiple strings, example of this -

Hello123
Halo123
Gracias
Thank you
...

I want grep to use these strings to find lines with matching strings/keywords from other files within a directory

example of text files being grepped -

123-example-Halo123
321-example-Gracias-com-no
321-example-match

so in this instance the output should be

123-example-Halo123
321-example-Gracias-com-no

Upvotes: 7

Views: 16730

Answers (3)

Or B
Or B

Reputation: 1803

I can think of two possible solutions for your question:

  1. Use multiple regular expressions - a regular expression for each word you want to find, for example:

    grep -e Hello123 -e Halo123 file_to_search.txt
    
  2. Use a single regular expression with an "or" operator. Using Perl regular expressions, it will look like the following:

    grep -P "Hello123|Halo123" file_to_search.txt
    

EDIT: As you mentioned in your comment, you want to use a list of words to find from a file and search in a full directory.

You can manipulate the words-to-find file to look like -e flags concatenation:

cat words_to_find.txt | sed 's/^/-e "/;s/$/"/' | tr '\n' ' '

This will return something like -e "Hello123" -e "Halo123" -e "Gracias" -e" Thank you", which you can then pass to grep using xargs:

cat words_to_find.txt | sed 's/^/-e "/;s/$/"/' | tr '\n' ' ' | dir_to_search/*

As you can see, the last command also searches in all of the files in the directory.

SECOND EDIT: as PesaThe mentioned, the following command would do this in a much more simple and elegant way:

grep -f words_to_find.txt dir_to_search/*

Upvotes: 0

Tom Drake
Tom Drake

Reputation: 537

You should probably look at the manpage for grep to get a better understanding of what options are supported by the grep utility. However, there a number of ways to achieve what you're trying to accomplish. Here's one approach:

grep -e "Hello123" -e "Halo123" -e "Gracias" -e "Thank you" list_of_files_to_search

However, since your search strings are already in a separate file, you would probably want to use this approach:

grep -f patternFile list_of_files_to_search

Upvotes: 2

Cyrus
Cyrus

Reputation: 88646

With GNU grep:

grep -f file1 file2

-f FILE: Obtain patterns from FILE, one per line.

Output:

123-example-Halo123
321-example-Gracias-com-no

Upvotes: 11

Related Questions