Strange behavior grep -rnw

I am using grep (BSD grep) 2.5.1-FreeBSD in MacOS and I have found the following behavior.

I have two *.tex files. Each one of these contains the following lines

$k$-th bit of
$(i-m)$-th bit of

respectively. When I ran

grep --color -rnw . -e '\$-th bit of' --include="*.tex" 

I got only the second file, i.e., $(i-m)$-th bit of, while I expect the two lines. Could you help me please to understand this behavior?

Upvotes: 1

Views: 287

Answers (2)

Ed Morton
Ed Morton

Reputation: 203985

Never use -r or --include or any other grep option to find files. The GNU guys really screwed up by adding those options to grep when there's a perfectly good tool named find for finding files and now they've turned grep into a convoluted mush of finding files and Globally matching a Regular Expression within a file and Printing the result (G/RE/P).

Keep it simple - find the files with find then g/re/p within then using grep:

find . -name '*.tex' -exec grep --color -n '\$-th bit of' {} +

As others pointed out your g/re/p problem was the -w arg so I've removed that above.

Upvotes: 1

Alex Harvey
Alex Harvey

Reputation: 15492

I have the same version of grep.

It is caused by your use of the -w option:

 -w, --word-regexp
         The expression is searched for as a word (as if surrounded by `[[:<:]]' and `[[:>:]]'; see re_format(7)).

The matched part of the string $k$-th bit of is bounded on the left-hand side by a word character (i.e. k) so the match is treated as being inside a "word" and it can't therefore satisfy the "searched for as a whole word" requirement.

Try without -w and it will work fine.

Upvotes: 0

Related Questions