Finding files containing a certain value

Searching for files containing a certain string/text/value is something that I do quite often. There are a number of ways to perform a “find files containing ‘foo'” search, but for me, nothing beats the simplicity and power of the command line!

In Windows:

findstr /s /n /i /p foo *

The above example of findstr will print out the relative file name/path and line number (/n) in a recursive (/s), case insensitive (/i) search for the string foo (foo) in all files (*), ignoring files with non-printable characters (/p).

For a literal string, you can use the /c option:

findstr /s /n /i /p /c:"foo bar" *

There are a number of other options, but those are the ones I use most often. To restrict your search to certain files, just change the * to the pattern you are looking for, like: *.txt or *.css, etc.

For Unix:

grep -rni foo *

The above example of grep will print out the relative file name/path, matching content and line number (-n) in a recursive (-r), case insensitive (-i) search for the string foo (foo) in all files (*).

To search for a literal string, just put the search pattern in quotes.

If you just want to see the relative file name/path and don’t care about the line number/content, you can use:

grep -rli foo *

And since these are commands I use all the time, I usually set up “shortcuts”, so that I don’t have to type out long commands with lots of options.

In Windows, you can create a batch file, called grep.bat for example, with the following:

findstr /s /n /p /i /c:"%1" %2

Then from the command line, just type grep foo *. For this to work, grep.batch needs to be in a folder that is in your PATH environment variable.

In Unix, there are a number of ways to do this, but I tend to just create an alias. For example, from the command line:

alias search='grep -rni'

Then from the command line, just type search foo *. Of course, you can just about any word/letter in place of search, just as long as it’s not a reserved/system keyword. Lastly, you can add the alias command to a startup file and it will be available to you every time you log in.

Scroll to Top