Searching for files containing a specific text string in Linux

The find and locate commands are great for finding files themselves, but sometimes you need to search for files that contain specific text. To accomplish this, you can use the grep command to perform a search.

Usage : grep "text string to search" directory-path

Below are some examples of how to search and how to filter your results a little more.

----------

For example, to search for the string "juicy apples" in all text files located in /home/bob/*.txt directory, use:

$ grep "juicy apples" /home/bob/*.txt

----------

If you want to search all for a text string in sub-directories recursively, use the -r switch, like this:

$ grep -r "juicy apples" /home/bob

----------

By default, grep command prints the matching lines. To print only filenames and the matching string, excluding the full location, you can use the -H switch to print just the filename and matching string for each match found, like this:

$ grep -H -r "juicy apples" /home/bob

Output:

...
filename.txt: juicy apples
...

----------

To just print only the filename and nothing else, use cut command as follows:

$ grep -H "juicy apples" /etc/* -R | cut -d: -f1

Output:

...
filename.txt
...



Was this answer helpful?

Add to Favourites Add to Favourites

Print this Article Print this Article

Also Read