How do I find all files containing specific text on Linux?

If you are looking for specific content but can’t remember where it’s located on the server, this post is for you. It will show you how to find specific text anywhere in a folder, or server.

We are going to use the GREP command when doing searches in linux.

grep searches input files for lines containing a match to a given pattern list. When it finds a match in a line, it copies the line to standard output (by default), or produces whatever other sort of output you have requested with options.

Here is an example of how you would use it:

grep -rnw '/path/to/somewhere/' -e 'pattern'

Each of the characters after “-” are known as options. These options allow you to invoke specific actions. For instance, here are the things you can do with this syntax:

  • -r or -R is recursive, where recursive means search everything
  • -n is line number, where it displays the line the text is located on the output
  • -w stands for match the whole word, ensure it doesn’t pick up parts only
  • -l (lower-case L) can be added to just give the file name of matching files.

There are other options that help you refine your query:

This will only search through those files which have .c or .h extensions:

grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"

This will exclude searching all the files ending with .o extension:

grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"

For directories it’s possible to exclude a particular directory(ies) through –exclude-dir parameter. For example, this will exclude the dirs dir1/, dir2/ and all of them matching *.dst/:

grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *