There are two ways to read all files under the current working directory:

  1. grep -rw pip | wc -l
  2. grep -r "\bpip\b" | wc -l

Assuming 1 and 2 both search the working directory for the whole word "pip", in 1 why does wc print the number of lines matching the pattern as 117 where as for 2 wc prints 74 as the number of lines?

Perhaps I don't understand how grep's recursive searches work. When grepping recursively does grep print only the files containing atleast one line that matches a pattern? So for example in the first command above 117 files under the current working directory contain a line matching the whole word "pip", similarly in the second command 74 files under the current working directory contain a line that matches the whole word "pip". Is this correct?

  • Good catch, can confirm. grep -r '\<pip\>' | wc -l gives same result as using the \b solution. – pLumo May 16 at 15:01
  • 1
    I know about differences between -w and \b and \<\> if you are applying them on non-word characters.. but in your case, you are using it on word characters, so I think something else is going on.. we'd need input sample to check it... could you create some minimal example where the two commands give different result? also, it should be 117/74 lines in your 2nd para, not files – Sundeep May 16 at 15:06
  • 1
    for 'I have 12, he has 2!' as sample input, grep -ow '..' and grep -o '\b..\b' and grep -o '\<..\>' will give different results – Sundeep May 16 at 15:08
  • -w will ensure that no word characters are present around the match, . doesn't care which character is matched.. it is something like (?<!\w)..(?!\w) in lookaround parlance.. I posted about this example in a github issue - check it out – Sundeep May 16 at 15:15
  • @OP, could you please check if the difference is only in binary files or also in text-only files. For me it's only binaries. Some control characters seem to make a difference here. diff <(grep -rw pip) <(grep -r '\bpip\b'). – pLumo May 16 at 15:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.