How do you search for specific text in specific file types?

13

4

Possible Duplicate:
How can I grep in source files for some text?

What's the command to search for specific text in specific file types, recursively, under the current directory?

Phillip

Posted 2011-08-25T21:35:07.440

Reputation: 431

Question was closed 2011-08-27T12:25:33.280

This is not a duplicate question. It is asking how to search over specific file types. This is very irritating because I want an answer to the question and there is no answer on this site because this question has been marked as a duplicate! – CJ7 – 2016-02-24T05:09:38.607

What do you want returned? the line the text is on? the name of the file the text is in? – MaQleod – 2011-08-25T21:49:21.607

@MaQleod: That would be good (filename + linenumber + snippet), if that's possible. – Phillip – 2011-08-25T21:51:37.833

@slhck: ack-grep is not installed; I don't have the permissions to install it. – Phillip – 2011-08-25T21:53:46.537

1You wouldn't need ack-grep, you can use the examples in the question as a started (just like I said), i.e. the find | xargs | grep lines. For the specific output, man grep is always useful to read. – slhck – 2011-08-25T21:55:22.817

@slhck: Thanks, so I did grep -r --include=*.<type> "<string>" ., which worked. Unfortunately, the man page is not very straightforward in mentioning the trailing dot. – Phillip – 2011-08-25T22:03:55.503

Yeah, the trailing dot is your current directory. Because it's basically grep <option> <something> <somewhere>, in your case <somewhere> is just . :) – slhck – 2011-08-25T22:05:26.037

Answers

11

find . -type f -name '*.extension' | xargs grep "string"

This command runs find on the local directory (.) for any files with names matching the pattern *.extension, then runs grep for "string" on the results of the find. Note that find is inherently recursive. As long as you can differentiate the files that you want from the files you don't based on name, this should work for you.

Fopedush

Posted 2011-08-25T21:35:07.440

Reputation: 1 723

Only find -print0 will not help, also use xargs -0: find . -type f -name "*.ext" -print0 | xargs -0 grep "string" – BurninLeo – 2014-10-07T12:16:23.127

2This breaks with filenames containing spaces, you should use the print0 option to be safer. – slhck – 2011-08-25T22:37:21.627

0

To list the file name, line number in specified file and line the text appears:

for x in *.xxx; do [ -r $x ] | cat $x | grep -n TEXT | xargs printf "$x:%s\n";done

It will only run in the current directory, but it will format it nicely for you.

MaQleod

Posted 2011-08-25T21:35:07.440

Reputation: 12 560