LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   how to make grep to search a pattern in only specific file type (https://www.linuxquestions.org/questions/linux-newbie-8/how-to-make-grep-to-search-a-pattern-in-only-specific-file-type-793645/)

mq15 03-06-2010 12:12 PM

how to make grep to search a pattern in only specific file type
 
Hello there;
To search a string pattern in all files in a directory and subdirectories, I am using;
Code:

grep -R "myclass::my-func(" mydirectory/
Now I want grep, to search in only specific file types say *.cc. Please help me. I have read manual of grep, but could not deduce any hint.
Best Regards.

troop 03-06-2010 12:21 PM

find mydirectory/ -name "*.cc" -type f -exec grep -l "myclass::my-func(" {} \;

mq15 03-06-2010 01:46 PM

Thanks troop,
The result of your command is exactly what I wanted. But I will take time to understand the command..

jlinkels 03-06-2010 06:59 PM

Troop is right, but this enhancement is quite useful:

Code:

find mydirectory/ -name "*.cc" -type f -exec grep -lH "myclass::my-func(" {} \;
It'll show you the name of the file this string was found in.

jlinkels

mq15 03-07-2010 01:27 AM

Thanks jlinkels, but I see no difference;

Code:

[mq15@localhost ns234]$ find ns-allinone-2.34/ -name "*.cc" -type f -exec grep -lH "::purge(" {} \;
ns-allinone-2.34/ns-2.34/queue/rtqueue.cc
ns-allinone-2.34/ns-2.34/aodv/aodv_rqueue.cc
ns-allinone-2.34/ns-2.34/aomdv/aomdv_rqueue.cc
[mq15@localhost ns234]$ find ns-allinone-2.34/ -name "*.cc" -type f -exec grep -l "::purge(" {} \;
ns-allinone-2.34/ns-2.34/queue/rtqueue.cc
ns-allinone-2.34/ns-2.34/aodv/aodv_rqueue.cc
ns-allinone-2.34/ns-2.34/aomdv/aomdv_rqueue.cc


troop 03-07-2010 05:22 AM

Quote:

Grep will list the filenames by default if more than one filename is given. The -H option makes it do that even if only one filename is given. In both your examples, more than one filename is given.
(c) http://stackoverflow.com/questions/1...ent-situations
I think in this case(when -l presented), this option is useless.
Probably he meant:
Code:

find ns-allinone-2.34/ -name "*.cc" -type f -exec grep -H "::purge(" {} \;
output: filename: string
or
Code:

find ns-allinone-2.34/ -name "*.cc" -type f -exec grep -n "::purge(" {} \;
output: filename:№ of string: string

jlinkels 03-07-2010 07:02 AM

Yes, -l already lists matching files, and -H lists the file name in addition to the matching string.

My preference is for -H as often I make mistakes in the regular expression so I wnat to see the matching string and I want to see in which file it is found.

-l als suffices in many cases of course.

jlinkels

mq15 03-07-2010 09:41 AM

Thanks to both of guys. Really useful information.
Have a nice day


All times are GMT -5. The time now is 10:50 AM.