Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use grep to search only in a specific file types?

Tags:

grep

I have a lot of files and I want to find where is MYVAR.

I'm sure it's in one of .yml files but I can't find in the grep manual how to specify the filetype.

like image 750
Tom-pouce Avatar asked Oct 24 '12 21:10

Tom-pouce


People also ask

How do I grep a specific file type?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do I grep recursively in a specific file?

To recursively search for a pattern, invoke grep with the -r option (or --recursive ). When this option is used grep will search through all files in the specified directory, skipping the symlinks that are encountered recursively.

How do I filter using grep?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".


3 Answers

grep -rn --include=*.yml "MYVAR" your_directory

please note that grep is case sensitive by default (pass -i to tell to ignore case), and accepts Regular Expressions as well as strings.

like image 55
Abraham P Avatar answered Oct 20 '22 07:10

Abraham P


You don't give grep a filetype, just a list of files. Your shell can expand a pattern to give grep the correct list of files, though:

$ grep MYVAR *.yml

If your .yml files aren't all in one directory, it may be easier to up the ante and use find:

$ find -name '*.yml' -exec grep MYVAR {} \+

This will find, from the current directory and recursively deeper, any files ending with .yml. It then substitutes that list of files into the pair of braces {}. The trailing \+ is just a special find delimiter to say the -exec switch has finished. The result is matching a list of files and handing them to grep.

like image 4
Ben Graham Avatar answered Oct 20 '22 05:10

Ben Graham


If all your .yml files are in one directory, then cd to that directory, and then ...

grep MYWAR *.yml

If all your .yml files are in multiple directories, then cd to the top of those directories, and then ...

grep MYWAR `find . -name \*.yml`

If you don't know the top of those directories where your .yml files are located and want to search the whole system ...

grep MYWAR `find / -name \*.yml`

The last option may require root privileges to read through all directories.

The ` character above is the one that is located along with the ~ key on the keyboard.

like image 2
Hitesh Avatar answered Oct 20 '22 07:10

Hitesh