17

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.

kryger
  • 12,906
  • 8
  • 44
  • 65
Tom-pouce
  • 758
  • 2
  • 11
  • 28

4 Answers4

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

Abraham P
  • 15,029
  • 13
  • 58
  • 126
  • Worth of mention that at least ZShell requires command argument `*.yml` to be quoted: `grep -rn --include="*.yml" "MYVAR" your_directory` Otherwise one will face no matches found error. More about issue: [https://stackoverflow.com/a/24197797/12172310] – Tumbelo Nov 24 '22 at 08:21
5

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.

Ben Graham
  • 2,089
  • 17
  • 21
3

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.

Hitesh
  • 296
  • 2
  • 8
0
find . -name \*.yml -exec grep -Hn MYVAR {} \;
MK.
  • 33,605
  • 18
  • 74
  • 111