Finding a File Containing a Particular Text String In Linux Server

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
Difficulty level Easy
Root privileges No
Requirements grep
Est. reading time Less than 2 minutes
You need to use the grep command. The grep command or egrep command searches the given input FILEs for lines containing a match or a text string.

grep command syntax for finding a file containing a particular text string

The syntax is:
grep "text string to search" directory-path
grep [option] "text string to search" directory-path
grep -r "text string to search"directory-path
grep -r -H "text string to search" directory-path
egrep -R "word-1|word-2" /path/to/directory
egrep -w -R "word-1|word-2" directory-path

Let us see some common example on how to use grep to search for strings in files.

How to search and find all files for a given text string

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
$ 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/
$ grep -R "redeem reward" /home/tom/
Look for all files containing cacheRoot text on Linux:
grep -R cacheRoot /home/vivek/

Trying to find all files containing specific text on my Linux desktop

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:


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 "" /etc/
grep --color -R -h "" /etc/
grep --color -R -h "" /etc/ 2>/dev/null

Sample outputs:

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/

How do I find all files containing specific text on Linux?

The syntax is:
egrep 'pattern' -rnw /path/to/dir/
egrep 'word1|word2' -rnw /home/vivek/backups/

Finding text strings within files using grep

In this example search for lines starting with any lowercase or uppercase letter:
grep "^[a-zA-Z]" -rns ~/projects/texts/

  • -r – Recursive search
  • -R – Read all files under each directory, recursively. Follow all symbolic links, unlike -r grep option
  • -n – Display line number of each matched line
  • -s – Suppress error messages about nonexistent or unreadable files
  • -w – Only work on words i.e. search only those lines containing matches that form whole words
  • -l – Show the name of each input file when match found
  • -i – Ignore case while searching

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 62 comments so far... add one

CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
62 comments… add one
  • memals Jan 5, 2008 @ 10:18

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

    • jeshwanth Mar 28, 2012 @ 5:52


  • Raja Mohammed Aug 4, 2009 @ 10:12

    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” /

  • Florian Sep 16, 2009 @ 8:26

    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” ?

  • Prashant Kumashi Oct 7, 2009 @ 10:29

    >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

    • Sharad Garg Oct 12, 2012 @ 6:13

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

  • Anonymous May 9, 2010 @ 4:32

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

    • clark Sep 30, 2011 @ 3:49

      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” {} \;

    • Davis Jul 6, 2013 @ 8:41

      This is what i was looking for Thank you

  • anon May 9, 2010 @ 4:34

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

    • Vatar May 13, 2010 @ 16:31

      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

  • Albert Dec 13, 2010 @ 20:58

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

    all file who have the word “hello” for example

    • Vivek Dec 14, 2010 @ 13:56

      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” .

      • Albert Dec 14, 2010 @ 17:10


        i found a nother way to do that:

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

        i hope this help someone

        • Vivek Dec 15, 2010 @ 13:24

          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

  • Russ Dec 15, 2010 @ 21:12

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

  • Me Dec 25, 2010 @ 8:56

    grep -Hr “TEXT_TO_FIND”

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

  • lindsey Mar 31, 2011 @ 1:45

    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.

    • lindsey Mar 31, 2011 @ 1:47

      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

  • Tlucz-huba Apr 23, 2011 @ 8:44

    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,


    • Carsten Jun 16, 2011 @ 8:35

      Hi T.,

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

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


  • chris pepper Aug 1, 2011 @ 13:14

    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

    • 🐧 nixCraft Aug 2, 2011 @ 7:14
      grep -r -- '-g' /home/user/src
    • Vivek M Garg Aug 2, 2011 @ 8:00

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

      It works in Linux.

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

      • chris Pepper Mar 7, 2012 @ 10:18

        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!

  • Karthick K Sep 1, 2011 @ 14:48


    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.

    Karthick K

  • alan Oct 29, 2011 @ 19:04

    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]

  • Search_it Nov 11, 2011 @ 11:21

    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.?

  • da_bull97 Nov 13, 2011 @ 6:12

    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?

  • shawn Dec 15, 2011 @ 18:17

    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

  • Marcelo Mar 6, 2012 @ 15:27

    Thank you! This is what I was looking for!

  • Robert Mar 17, 2012 @ 23:20

    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.

    • chris Pepper Mar 19, 2012 @ 10:06

      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 Pepper Mar 19, 2012 @ 10:10

        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”

        • chris Pepper Mar 19, 2012 @ 10:13

          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

  • Amani Musomba Mar 26, 2012 @ 23:48

    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.

  • leming Apr 16, 2012 @ 7:58

    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

  • Bitcoin Game Jun 4, 2012 @ 14:37

    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.

  • chris Pepper Jun 6, 2012 @ 9:48

    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.

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

  • Chao Huang Jun 18, 2012 @ 22:53

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

  • Chao Huang Jul 6, 2012 @ 15:33

    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

  • cmsbuffet Jul 17, 2012 @ 14:13

    Thank you.
    I found the files

  • manoharan g Sep 15, 2012 @ 14:14

    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?

  • IJK Feb 26, 2013 @ 1:05

    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”

  • Itman Mar 5, 2013 @ 20:40

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


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

    you will only get list of unique filenames.

  • Vivek Rana Nov 22, 2013 @ 7:00

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

  • LinuxCurious Feb 1, 2014 @ 5:43

    it’s not working …

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

    I am using ubuntu 13.10

    • LinuxCurious Feb 1, 2014 @ 5:44

      Even I have the directory under it.

  • Craig Mar 11, 2014 @ 17:45

    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 ?

  • Kratos Mar 12, 2014 @ 9:08

    Nice article, thanks.

  • Allysson May 14, 2014 @ 20:28

    Thanks ! i had find my files

  • monty Jun 4, 2014 @ 7:38

    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

  • Allysson Jun 17, 2014 @ 12:46

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

  • Max Jun 24, 2014 @ 18:09

    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

  • Help!!! Sep 21, 2014 @ 16:08

    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.

    • Amani Musomba Sep 25, 2014 @ 18:01

      You can try
      grep mingo flashcomic*

  • Zeba Dec 8, 2014 @ 7:57

    grep -il *

  • Zeba Dec 8, 2014 @ 7:57

    grep -il match_string *

  • vinay Apr 24, 2015 @ 11:31

    thanks a lot, this is good stuff

  • AK Oct 2, 2015 @ 12:28

    I need help in the following situation. Thanks in advance.
    I have a text file named “a.txt” which contains the hash values of few thousand files. Next i have a folder containing few thousand text files and each file must have one hash value from which we can recognize individual text file.Now, i want to read each line of “a.txt” and want to search through the directory to find which file contains the particular hash value. Once found the file should be moved to some other folder.
    Can any body help in how can i perform this task?

  • abbas Aug 7, 2017 @ 9:53

    help me to learn all linux commad

  • Maaza Aug 20, 2020 @ 15:05

    I have group of control scripts with a specific path /apps/dev01/app/xxx/bin/xxx.ctl, where I will be having the entry for port number
    something like, ‘-Dserver.port=8111’.

    Question: Is is possible to list it like a table with results,

    app name        | Port
    xxx             | 8111
    yyy             | 8212

    and so on?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum