About Linux FAQ

Browse More FAQs:

Finding a File containing a particular text string in Linux server

Posted by Vivek on Saturday March 24, 07 @4:47 am

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:

Discussion on This FAQ

  1. memals Says:

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

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!

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

~ Last updated on: March 24, 2007

Copyright © 2006-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.