regexlinuxgreppunctuation

Am I using caret symbol correctly with grep?


This does not work

grep -h '^zip' log*

this works

grep -h '[^bg]zip' log*

The log* files definitely contain a file named zip because the second command prints out the file name. But the first does not print anything at all. I try several and see that the caret symbol only works as negation in brackets. Outside of the bracket, it does not mean to indicate that something following it would be in the beginning of the word. What is wrong here? I am using ubuntu 12.4


Solution

  • beginning of the word

    ^ marks the beginning of line, not word. "foo zip" will not match against ^zip, but "zip foo" will. If you want to match zip at the beginning of a word, use this:

    grep \\bzip
    

    \b marks a word boundary, but you need to double up on escapes because your shell will strip one. (grep '\bzip' also works.)