I've got a bunch on strings which I need to find in a couple of files, for example:



Is there an (easy) way to do that in bash? I need to know, if a string was found, in which file is it.


6 Answers 6


Simple grep command with -e option:

 grep -e "string1" -e "string2" -e "stringn" file*.txt

Or you can put all the search strings in a file called search.txt like this:


and then run grep like this with -f option:

grep -f search.txt file*.txt
  • you can use stdin as file echo -e "string1\nstring2\nstringn" | grep -f - search.txt file*.txt
    – jcubic
    Apr 28, 2011 at 15:24

Use grep to search for all the strings in one pass:

grep -E -H 'string1|string2|stringn' file1.txt file2.txt filen.txt

The -E lets you use the pipe character(|) without escaping it. The -H prints the filename for each match. The regular expression uses pipes to separate each string, so that grep will try to match each one in order.


There is a variant of grep that supports this feature for large sets of strings, try


fgrep -f ${fileWithListOfSearchTargets} file1 file2 ... filen

(The variable and filenames are meant to be self-documenting, you can use any name you like)

You have to enter all your search strings into the file.

No leading or trailing spaces unless you expect those to match in your filelist. There is a limit to the size that most fgreps can process. Don't try to cram 10K lines into one file.


The best way is to use grep:

grep -H 'string to search' file1.txt file2.txt filen.txt

will search the specified files for a string, and print out the matching lines along with the filename where the match was found.

  • And if you need to do this for an arbitrary number of strings, enclose it in a for loop. For example: for searchString in "string1 string2 stringn"; do grep -H $searchString file1.txt file2.txt; done However, this assumes that searchString is an easy word -- if it has symbols, spaces, you need more escaping.
    – Mike R
    Apr 28, 2011 at 15:13

Unix find command:

find . -exec grep "i want to find this string" '{}' \; -print

will search from current dir and down.

This works too:

egrep -r 'arbitrary string' *
  • The use of find here does not add anything that grep cannot do by itself. Of course find COULD be used to a purpose to find a useful set of files to send to grep, but in this case grep would be able to do the same with with the -R flag and save a lot of mess.
    – Caleb
    May 7, 2011 at 11:15
egrep "(string1|string2|string3)" file{1..3}.txt
  • This adds nothing useful not covered in other answers. If you want to show alternate syntax consider commenting on one of the other answers instead.
    – Caleb
    May 7, 2011 at 11:14
  • I introduced the syntax of curly braces, to address multiple files. We had the discussion already on meta. May 7, 2011 at 12:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .