Finding a File containing a particular text string in Linux server

by Vivek Gite · 4 comments

Q. I've been using Linux for a while on my server and have a large collection of text file everywhere. I’m interested in learning about searching a text string. Can you tell me - how do I find a file containing a particular text string in Linux server?

A. I have to admit that there are tens and thousands of text files in Linux server. Finding and locating those files can be done with find command. Unfortunately find command cannot look inside a text file for a string.

You need to use grep command. grep searches the given input FILEs for lines containing a match or a text string.

grep command form (syntax)

grep “text string to search” directory-path

Examples

For example search for a string called redeem reward in all text files located in /home/tom/*.txt directory, use
$ grep "redeem reward" /home/tom/*.txt

Task: Search all subdirectories recursively

You can search for a text string all files under each directory, recursively with -roption:
$ grep -r "redeem reward" /home/tom

Task: Only print filenames

By default, grep command prints the matching lines You can pass -H option to print the filename for each match.
$ grep -H -r “redeem reward” /home/tom
Output:

...
filename.txt: redeem reward
...

To just print the filename use cut command as follows:
$ grep -H vivek /etc/* -R | cut -d: -f1
Output:

...
filename.txt
...

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 4 comments… read them below or add one }

1 memals 01.05.08 at 10:18 am

grep -l ‘redeem reward’ /path
gives just the file names and -lr would do it recursively

2 Raja Mohammed 08.04.09 at 10:12 am

If you want to find the exact string use the -w option.
for Example to find the whole word “Redeem Reward”,
grep -H -r -w “Redeem Reward” /

3 Florian 09.16.09 at 8:26 am

Ok, this is a difficult one:
How would you look for all files named “file1″ OR “file2″ which are somewhere (recursively) in “/home/tom” and contain the string “Redeem Reward” ?

4 Prashant Kumashi 10.07.09 at 10:29 am

>Ok, this is a difficult one:
>How would you look for all files named “file1″ OR “file2″ which are somewhere >(recursively) in “/home/tom” and contain the string “Redeem Reward” ?

You can use following command:
grep -r "redeem reward" /home/tom | grep file1

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous FAQ:

Next FAQ:

nixCraft FAQ PDF Collection Now Available To All