grep -w is not unique if dash is in string

Viewed 774

iIf a dash is in the string "grep -w" is not unique. How can I solve this?

Example:

File1:

football01
football01test

# grep -iw ^football01
football01

File2:

football01
football01-test

# grep -iw ^football01
football01
football01-test
2 Answers

This is the expected and documented behaviour:

   -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.

If you add a dash, it terminates your first word as a dash is a "non-word constituent character". If you write the words together, then a word-regexp grep will treat it as one word and not match it.

What exactly it is that you want to do?

If you only want to know if your line is football01 and nothing else, you can do it as

grep -i "^football01$"

If you want to achieve something else, could you please explain what it is.

The -w switch is for word regex. In file1, football01test is a word and in file2 football01 and test are two words separated by a hyphen.

man grep says this for -w

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.

Since football01 doesn't match football01test as a whole word, you aren't getting that info from grep.

If you were to do grep -i ^football01 file1.txt, you will get both lines.

Related