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:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- My 10 UNIX Command Line Mistakes
- 10 Greatest Open Source Software Of 2009
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email FAQ to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: 03/24/07



{ 4 comments… read them below or add one }
grep -l ‘redeem reward’ /path
gives just the file names and -lr would do it recursively
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” /
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” ?
>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