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
...

  • 3 Users Found This Useful
Was this answer helpful?

Related Articles

How to change the target of a symbolic link

To change the target of a symbolic link in linux, you can use the following command. ln -f -s...

Changing permissions on directories only

You may need to change permissions for directories under a directory tree, without changing...

Monitor Linux software RAID array with e-mail notification

When using software RAID on Linux, one fast way to know the status of your RAID array is to check...

Powered by WHMCompleteSolution