Finding a File Containing a Particular Text String In Linux Server

by on March 24, 2007 · 58 comments· LAST UPDATED May 30, 2013

in , ,

I have been using Linux for a while on my server and have a large collection of the 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 on my Linux server?

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

Tutorial details
DifficultyEasy (rss)
Root privilegesNo
Requirementsgrep
Estimated completion timeLess than 2 minutes
You need to use the grep command. The grep command searches the given input FILEs for lines containing a match or a text string.

grep command syntax

The syntax is:

grep "text string to search” directory-path

OR

grep [option] "text string to search” directory-path

OR

grep -r "text string to search” directory-path

OR

grep -r -H "text string to search” directory-path

OR

egrep -R "word-1|word-2” directory-path

OR

egrep -w -R "word-1|word-2” directory-path

Examples

In this example, search for a string called 'redeem reward' in all text (*.txt) files located in /home/tom/ directory, use:
$ grep "redeem reward" /home/tom/*.txt
OR
$ grep "redeem reward" ~/*.txt

Task: Search all subdirectories recursively

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

Task: Only display filenames

By default, the 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
Sample outputs:

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

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

filename.txt
foobar.txt
...

Task: Suppress file names

The grep command shows output on a separate line, and it is preceded by the name of the file in which it was found in the case of multiple files. You can pass the -h option to suppress inclusion of the file names in the output:
$ grep -h -R 'main()' ~/projects/*.c

Task: Display only words

You can select only those lines containing matches that form whole words using the -w option. In this example, search for word 'getMyData()' only in ~/projects/ dirctory:
$ grep -w -R 'getMyData()' ~/projects/

Task: Search for two or more words

Use the egrep command as follows:
$ egrep -w -R 'word1|word2' ~/projects/

Task: Hide warning spam

grep command generate error message as follows due to permission and other issues:

No such file or directory
No such device or address
Permission denied

To hide all errors or warning message spam generated by the grep command, append 2>/dev/null to grep command. This will send and hide unwanted output to /dev/null device:
$ grep -w -R 'getMyData()' ~/projects/ 2>/dev/null

Task: Display matched text in color

Pass the --color option to the grep command display matched text/words in color on the terminal:

 
grep --color 'word' file
grep --color -R 'word' /path/to/dir
grep --color -R "192.168.1.5" /etc/
grep --color -R -h "192.168.1.5" /etc/
grep --color -R -h "192.168.1.5" /etc/ 2>/dev/null
 

Sample outputs:

Fig.01: grep command in action with colors and hiding the warnings on screen

Fig.01: grep command in action with colors and hiding the warnings on screen

Task: Ignore case

Our final example ignore case distinctions in both the search PATTERN and the input files:
grep -i -R 'word' /path/to/dir
grep -i -r 'income tax' ~/accounting/

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 58 comments… read them below or add one }

1 memals January 5, 2008 at 10:18 am

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

Reply

2 jeshwanth March 28, 2012 at 5:52 am

Thanks

Reply

3 Raja Mohammed August 4, 2009 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” /

Reply

4 Florian September 16, 2009 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” ?

Reply

5 Prashant Kumashi October 7, 2009 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

Reply

6 Sharad Garg October 12, 2012 at 6:13 am

Search for a string in all xml files recursively inside a directory.
find -name “*.xml” -exec grep -l “slc02oxm.us.oracle.com” {} \;

Reply

7 Anonymous May 9, 2010 at 4:32 am

find . -type f -exec grep -i “redeem reward” {} \; -print

Reply

8 clark September 30, 2011 at 3:49 am

for my version of linux, I had to move the -print in front. plus i added some params for grep

find . -type f -print -exec grep -inH “redeem reward” {} \;

Reply

9 Davis July 6, 2013 at 8:41 am

This is what i was looking for Thank you

Reply

10 anon May 9, 2010 at 4:34 am

find . -type f -exec grep -i “redeem reward” {} \; -print

Reply

11 Vatar May 13, 2010 at 4:31 pm

find . -type f -exec grep -i “redeem reward” {} \; -print 2>/dev/null
to get rid of
grep: can’t open ./var/adm/log/secret.log

Reply

12 Albert December 13, 2010 at 8:58 pm

how can i search for a specific file content and delete them like a:

all file who have the word “hello” for example

Reply

13 Vivek December 14, 2010 at 1:56 pm

Let’s assume:-
files to search = *.txt
Directory to be searched=/tmp
search string=hello
Let’s also assume that file names *.txt also contain blank spaces as
“/tmp/1st file.txt”
First verify that you get the names of the correct files to be deleted as follows:

# find /tmp -type f -name ‘*.txt*’ | sed -e ‘s/.*/\”&\”/’ |xargs -n 1 grep -l hello|sed -e ‘s/.*/\”&\”/’

( Here sed is used to deal with blank spaces within file names )

After confirming that the results are ok, files can be deleted by piping & xargs as follows:

# find /tmp -type f -name ‘*.txt*’ | sed -e ‘s/.*/\”&\”/’ |xargs -n 1 grep -l hello|sed -e ‘s/.*/\”&\”/’|xargs -n 1 rm -f

Note: If the search string has blank spaces, place the entire “search string” within “Double quotes” .

Reply

14 Albert December 14, 2010 at 5:10 pm

thanks!!!

i found a nother way to do that:

find /home/ -exec grep -l “mp3″ {} \; | xargs rm

i hope this help someone

Reply

15 Vivek December 15, 2010 at 1:24 pm

Welcome !

Yes it’s short & better for sure. Did not try with -exec earlier.
Perfect if there are no blank spaces / special characters in file names.

Take care.
Vivek M Garg

Reply

16 Russ December 15, 2010 at 9:12 pm

great people, helpful but what Vivek write is for me to difficult. May be it’s time to start learning sed or awk :-)
Thx2all

Reply

17 Me December 25, 2010 at 8:56 am

grep -Hr “TEXT_TO_FIND”

i.e. grep -Hr “Me” /home/earth

Reply

18 lindsey March 31, 2011 at 1:45 am

hi all, kind of a continuation of the original Q but need text from the “process table” in AIX not a file:
java process & need to parse out anything “-Xm”, appreciate any help, been banging my head trying: awk, cut, sed (noob here), perl (noob here) and it kinda works but i have to figure out the “positions of the fields” i need to make them work ($15,$16,$NF), i need a way to parse an unknown ‘position in a string’. hope this makes sense, thx much.

Reply

19 lindsey March 31, 2011 at 1:47 am

this works but again, i have to know hte positions to make it work correctly:
# ps -aefk | awk ‘/-Xm/ {print $14,$15,$NF}’
-Xms256m -Xmx1024m server1
-Xms50m -Xmx256m nodeagent

Reply

20 Tlucz-huba April 23, 2011 at 8:44 am

Hi guys,

can you please help me out with a grep command to find a 16 chars long string that starts with number ‘2012’ and then followed by any characters?

Thank you,

T.

Reply

21 Carsten June 16, 2011 at 8:35 am

Hi T.,

use: grep “\b2012.\{12\}\b”

That means: any word (marked by \b) starting with 2012 followed by any character (“.”) repeated 12 times.

Carsten

Reply

22 chris pepper August 1, 2011 at 1:14 pm

how do i search for a string containing “-g” ?? whenever i do
grep -r “-g” /home/user/src

it says “invalid option -g” how do i stop it picking it up as an option? I also tried

grep -r “cc” /home/user/src/*.mak and it says:
” /home/user/src/*.mak: no such file or directory” is this because of the -r option?

I appreciate any help!

-Thanks, Chris

Reply

23 nixCraft August 2, 2011 at 7:14 am
grep -r -- '-g' /home/user/src

Reply

24 Vivek M Garg August 2, 2011 at 8:00 am

Can also try grep -r “\-g” /home/user/src

It works in Linux.

— ‘-g’ also works as sugested by Vivek Gite

Reply

25 chris Pepper March 7, 2012 at 10:18 am

Thanks Guys :)

Sorry for the late reply I gave up on this for a while and i was just reminded by an update on the site!

I really appreciate your help i shall give that a whirl next time i boot linux!

Reply

26 Karthick K September 1, 2011 at 2:48 pm

Hi

I have to move n number of files from one path to another path. No matter what the file name is. Can I get the command for doing this? Unix as well as in Windows.

Any help is appreciated.

Thanks,
Karthick K

Reply

27 alan October 29, 2011 at 7:04 pm

I am totally green in this… can anyone tell me how to find files which contain the same name of file and the same string in file? [name of file = file contain the same string/ text as name of the file]

Reply

28 Search_it November 11, 2011 at 11:21 am

Hello,
I want to search string ,but i dont know that string present in which file name or where it is present.Is there any unix command for searching such kind of string.?

Reply

29 da_bull97 November 13, 2011 at 6:12 am

I have an interesting question that ive been searching for a long time. would there be any way, to use a grep command to search for files based on words found in a text file?

for example, lets say i have a text file with the names of a bunch of songs i want to delete from directory /home/music. I want to be able to create a script that would search for the songs in /home/music from the text file.

any ideas?

Reply

30 shawn December 15, 2011 at 6:17 pm

re: da_bull97, i’ve recently been hacked, and I used this command to find a specific word on my server throughout 100+ sites > and save the result to a text file.

grep -r “base64_decode” /home/ > /home/domain/public_html/results.txt

Reply

31 Marcelo March 6, 2012 at 3:27 pm

Thank you! This is what I was looking for!

Reply

32 Robert March 17, 2012 at 11:20 pm

I need to search all .txt-files on my hard drive for å specific string, how do I do that? If I try it searches every single file in all folders and takes forever. If I try it searches only the *.txt-files but only in the current folder.

Reply

33 chris Pepper March 19, 2012 at 10:06 am

This one i have used that i think would do the trick for you:

find . -name “*.[txt|TXT]” -print | xargs grep “specific string”

Hope that helps,
Chris

Reply

34 chris Pepper March 19, 2012 at 10:10 am

although i would recommend adding “-HnT” to the grep to get file names, line numbers and it lined up nicely. So the full command would be:

find . -name “*.[txt|TXT]” -print | xargs grep -HnT “specified string”

Reply

35 chris Pepper March 19, 2012 at 10:13 am

I have also assumed you want to search within those files, if you are just searching for a file name with a specific string, drop the xargs

sorry for the repeated posts :p

Reply

36 Amani Musomba March 26, 2012 at 11:48 pm

I used the below command and it worked perfectly for me.
find / -type f -print0 | xargs -0 grep -i pattern
This command will look for every file in the system and search a (case insensitive) pattern using grep.

Reply

37 leming April 16, 2012 at 7:58 am

this will print list all of files which under assign directory include even those files which doesnot contain a searched word doesnot contain even single word which actyall\y even not a text file.
same output as if i use ls -r

Reply

38 Bitcoin Game June 4, 2012 at 2:37 pm

How would one search directories recursively, but exclude certain files?

Like grep -r /home/www/ -exclude hugemovie.avi

I think my grep search is very slow because it’s going through some very large binary files, when I only really want to search through *.php.

Reply

39 chris Pepper June 6, 2012 at 9:48 am

Out of interest if all you really want to do is search through .php why can’t you use something to only search through .php? find should work recursively already.

e.g:
find . -name “*.[php|PHP]” -print
or
find . -name “*.[php|PHP]” -print | xargs grep -HnT “specified string”

Reply

40 Chao Huang June 18, 2012 at 10:53 pm

use
grep -r “redeem reward” /home/tom/*/*.txt
to search for a text string in text files under all subdirectories.

Reply

41 Chao Huang July 6, 2012 at 3:33 pm

use
grep -l -r “redeem reward” /home/tom -R | cut -d: -f1
to show the file name only. No repeated name, just like search in Windows Vista/7

Reply

42 cmsbuffet July 17, 2012 at 2:13 pm

Thank you.
I found the files

Reply

43 manoharan g September 15, 2012 at 2:14 pm

sir i need a small shell script in Linux to find out loading time of programe and running time of given programme.
can you help me?

Reply

44 IJK February 26, 2013 at 1:05 am

The below command shows the results with the file name and jar file name.

To find the string in the list of jar file.

find -name “*.jar” -print -exec zipgrep “jar$|” ‘{}’ \;

To find the class name in the list of jar file.

find . -name “*.jar” -print -exec jar tvf {} \; |grep -E “jar$|.class”

Reply

45 Itman March 5, 2013 at 8:40 pm

It also could be useful to sort output and remove duplicates using ‘sort -u’

Using

sudo grep -Hr pure-ftpd /etc/ | cut -d: -f1 | sort -u

you will only get list of unique filenames.

Reply

46 Vivek Rana November 22, 2013 at 7:00 am

I want to find the line in a file say ‘file1′ inside a directory ‘log’ containing word ‘Complete :’

Reply

47 LinuxCurious February 1, 2014 at 5:43 am

it’s not working …

grep -h -R ‘main()’ ~/projects/*.c
No such file or directory

I am using ubuntu 13.10

Reply

48 LinuxCurious February 1, 2014 at 5:44 am

Even I have the directory under it.

Reply

49 Craig March 11, 2014 at 5:45 pm

I had a task to take an image of a drive, and find a string allt-na-reigh.
After creating a text file called patternfile containing allt-na-reigh.. I used grep -abif patternfile harddiskimage.dd

Now the -b switch printed out the byte offset 27405973..

But how do i find the original file that the text is in ?

Reply

50 Kratos March 12, 2014 at 9:08 am

Nice article, thanks.

Reply

51 Allysson May 14, 2014 at 8:28 pm

Thanks ! i had find my files

Reply

52 monty June 4, 2014 at 7:38 am

Hi All,

I would like to seach some text in file no1.
The search result from file 1 i have to find it in file no2.
Again the search result in file2 has to be find it in file no3.

Can you anyone tell me or write a script for me in linux?

Thank you
Regards
Monty

Reply

53 Allysson June 17, 2014 at 12:46 pm

Nice! more useful in the complex files and projects thanks!

Reply

54 Max June 24, 2014 at 6:09 pm

Hiya so I have this issue when the searching is Don, the result iget is slightly weird I dont know how to get rid of it.
This is my code: grep -H -r “test” /home/pi/*.desktop | grep file1 ~/projects/ 2>/dev/null

The output I get is slightly weird /home/pi /file1.desktop:test

Reply

55 Help!!! September 21, 2014 at 4:08 pm

I need to search someof the files in my current directory for the string “mingo”. All of the files which are of interest to me have the form flashcomicXXX.txt, where XXX is a 3-digit number.

Reply

56 Amani Musomba September 25, 2014 at 6:01 pm

You can try
grep mingo flashcomic*

Reply

57 Zeba December 8, 2014 at 7:57 am

grep -il *

Reply

58 Zeba December 8, 2014 at 7:57 am

grep -il match_string *

Reply

Leave a Comment

Tagged as: , ,

Previous Faq:

Next Faq: