April 21

Linux: Finding a File containing with a particular text (grep)

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

By: Nixcraft


Copyright 2021. All rights reserved.

Posted April 21, 2013 by Timothy Conrad in category "Linux

About the Author

If I were to describe myself with one word it would be, creative. I am interested in almost everything which keeps me rather busy. Here you will find some of my technical musings. PGP: 4CB8 91EB 0C0A A530 3BE9 6D76 B076 96F1 6135 0A1B