Finding a File Containing a Particular Text String In Linux Server

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/

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.