Grep – Pattern Matching with Dashes and Filename Extension Restriction

grep

I am trying to use grep to find some tex files containing the pattern ->-:

grep -R -- "->-" *.tex

But this doesn't work. If I do:

grep -R -- "->-"

instead, it works, but is really slow and gives me clearly not only tex files but also matches lots of other file (for example binary files).

What would be the fastest way to do this search?

Best Answer

The problem is that -R tells grep to recursively search through all files in the directory. So, you can't combine it with a specific group of files. Therefore, you can either use find as suggested by @KM., or shell globbing:

$ shopt -s globstar
$ grep -- "->-" **/*.tex

The shopt command activates bash's globstar feature:

globstar
                  If set, the pattern ** used in a pathname expansion con‐
                  text will match all files and zero or  more  directories
                  and  subdirectories.  If the pattern is followed by a /,
                  only directories and subdirectories match.

You then give **/*.tex as a pattern and that will match all .tex files in the current directory and any subdirectories.

If you're using zsh, there's no need for the shopt (which is a bash feature anyway) since zsh can do this by default.

Related Question