How to Find All Files Containing Specific Text on Linux

Many recent file managers support file searching directly in the file list. Anyway, most of them do not let you search inside the contents of a file. Here are some methods you can use to search for file contents on Linux using the command line. In this snippet, we’ll present the "grep", "ripgrep", "ack" and "find" commands.

Use the grep command

The best way of finding files that contain a specific text is by using the grep command. It is designed to find the files containing the necessary text according to patterns in the entire data streams. You need to use the following command:

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

Here, r stands for recursive, n refers to a line number, w is used to match the whole word, '/path/to/somewhere/' is the directory, and 'pattern' is the text you’re looking for in files.

To make your search more effective, you can also add such optional settings as --exclude, --include, --exclude-dir.

  • To search only through files having .c or .h extensions, use the following:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
  • To exclude the search of all the files that end with .o extension, try this:
grep --exclude=*.o -rnw '/path/to/somewhere/' -e "pattern"
  • To exclude a particular directory from your search, you need this:
grep --exclude-dir={dir1,dir2,*.dst} -rnw '/path/to/somewhere/' -e "pattern"

You can also run another command line with grep:

grep -iRl "your-text-to-find" ./

Here i stands for ignoring the case, R stands for recursive, I is used to display the file name, not the result itself, and ./ stands for starting at the root of your machine.

Use the ripgrep command

An alternative use for grep is ripgrep. If you're working on large projects or big files, you had better use ripgrep. It will look like this:

rg "your-text-to-find" /

Use the ack command

This command will allow you to search in the entire file system or the needed path. It can be easier to use than grep.

  • To search in the current path, use the following command line:
ack "your-text-to-find"
  • To search in the entire file system, change the directory to the root (/) like this:
ack "your-text-to-find" /
For ripgrep and ack commands, use regular expressions to specify the file type.

Use the find command

You can also combine the find and grep commands to search for text strings in many files more effectively.

# find / -exec grep -l "your-text-to-find" {} ;

To search in specific file extension files, like search ‘your-text’ in all php files only, use the following command:

# find / -name '*.php' -exec grep -l "your-text" {} ;