2

I am trying to use grep to find the string "crk" in a file. I know the string exists in a c source file in the form

kop.crk_op = CRK_MOD_EXP;

However, when I search using

 grep -rnw --include '*.c' '.' -e "crk"

I get an empty result. The line

 grep -rnw --include '*.c' '.' -e "crk_op"

works just fine, but that really isn't helpful to me. I assume the '_' character is somehow messing up my search. How can I modify my approach to match all strings of which "crk" is a substring, even when the '_' character is present, or any other character for that matter?

Edit: It seems I got a bit trigger happy on this post. The command

grep -rnw --include '*.c' '.' -e "[^ ]*crk[^ ]*"

seems to work. Alternatively, can someone explain why the extra wildcards are needed?

1 Answer 1

4

The -w option makes grep look for words, so it will show crk when surrounded by non-word characters. From man grep:

-w, --word-regexp
      Select  only  those  lines  containing  matches  that form whole
      words.  The test is that the matching substring must  either  be
      at  the  beginning  of  the  line,  or  preceded  by  a non-word
      constituent character.  Similarly, it must be either at the  end
      of  the  line  or  followed by a non-word constituent character.
      Word-constituent  characters  are  letters,  digits,   and   the
      underscore.

_ is a word character, so crk_op will not match crk with -w.

The convoluted regex "[^ ]*crk[^ ]*" works because it allows any number of non-space characters between the word boundaries that grep requires.

Just do:

grep -rn --include '*.c' . -e crk

You don't need to qoute . for the current directory there.

2
  • Hmmm, so '_' is a word character but '[', for example, is not. How odd...
    – Aroto
    Apr 5, 2017 at 5:43
  • @user3813122 not particularly so, if you know a but of programming history. _ has been allowed in variable names since around the time grep was created (at least), and it's only natural to see a variable name as a word.
    – muru
    Apr 5, 2017 at 5:45

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.