Finding a File Containing a Particular Text String In Linux Server

Posted on in Categories , , , last updated May 30, 2013

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.

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/

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

61 comment

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

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

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

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

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

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

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

    all file who have the word “hello” for example

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

      1. thanks!!!

        i found a nother way to do that:

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

        i hope this help someone

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

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

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

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

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

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

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

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

      It works in Linux.

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

      1. 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!

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

  10. 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]

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

  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?

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  25. it’s not working …

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

    I am using ubuntu 13.10

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

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

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

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

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

Comments are closed.