Finding a File containing a particular text string in Linux server
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 ...
Subscribe to our free e-mail newsletter or RSS feed to get all updates.
You can Email this page to a friend.
Related Linux / UNIX FAQ:
- UNIX / Linux: vi / vim perform search and replace operation
- Search all the Linux man pages for a particular command or text
- Search Multiple Words / String Pattern Using grep Command
- How To Search Shell Command History
- Howto use grep command in Linux / UNIX
Discussion on This FAQ
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Please do not use the comment form to ask for help / question. Ask your question on the excellent Linux tech support forum. Thank you very much for stopping by our site!
~ Last updated on: March 24, 2007



January 5th, 2008 at 10:18 am
grep -l ‘redeem reward’ /path
gives just the file names and -lr would do it recursively