3

I need to grep words like these:

ABC-DEF
AB2-DEF
AB3-DEF
AB-DEF

So I was trying:

grep AB*-DEF
grep -w -AB*-DEF
grep -w AB*DEF

But neither of them are working.

Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
GP92
  • 775
  • 6
  • 15
  • 31

4 Answers4

13

* in a regex is not like a filename glob. It means 0 or more of the previous character/pattern. So your examples would be looking for a A then 0 or more B then -DEF

. in regex means "any character" so you could fix your pattern by using

grep 'AB.*DEF'
Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Eric Renouf
  • 18,141
  • 4
  • 49
  • 65
3

As far as your patterns are concerned, this would be the safest to match only intended strings:

grep 'AB.\{0,1\}-DEF' file.txt

Or

grep -E 'AB.?-DEF' file.txt

. matches any single character, ? and \{0,1\} matches the previous token zero or one time, so in total .? and .\{0,1\}will match zero or one character before -DEF.

If you use AB.*-DEF or AB.*DEF, grep will greedily match unintended strings, for example:

ABCG-DEF
ABCGLHHJKH90-DEF
heemayl
  • 54,820
  • 8
  • 124
  • 141
1

You can use:

grep 'AB.*-DEF' file.txt
cuonglm
  • 150,973
  • 38
  • 327
  • 406
nghnam
  • 129
  • 4
  • 3
    That command crashed my machine. I had a `AB.\(a*\)\{10000\}-DEF` file in the current directory. – Stéphane Chazelas May 13 '15 at 15:06
  • I edited my post, quoted the search pattern. Thank you. – nghnam May 13 '15 at 15:22
  • @nghnam: Please take time to edit your answer [here](http://unix.stackexchange.com/a/203116/38906), too. Or deleting it, otherwise other people will be confused with the information in that answer. – cuonglm May 13 '15 at 15:31
0

The wildcards in your regular expressions are expanded by the shell. The shell treats them as filename metacharacters. So, you have to tell the shell to not evaluate them as filename metacharacters and you do that by quoting them using single quotes, double quotes, or backslash character just before the metacharacter. Then, the shell sends the expression as such to the grep utility which handles the regular expression.

unxnut
  • 5,908
  • 2
  • 19
  • 27