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.

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'
|improve this answer|||||
  • This will match many other patterns e.g. ABCGLHHJKH90-DEF – heemayl May 13 '15 at 18:26
  • 1
    True heemayl, but it is in keeping with the filesystem glob expansion like Jeevan seemed to be trying for in the question. – Eric Renouf May 13 '15 at 18:40
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
|improve this answer|||||
1

You can use:

grep 'AB.*-DEF' file.txt
|improve this answer|||||
  • 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, 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.

|improve this answer|||||

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