Wildcards for filepaths aren't working in grep
18,991
Solution 1
*
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'
Solution 2
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
Solution 3
You can use:
grep 'AB.*-DEF' file.txt
Related videos on Youtube
Author by
GP92
Updated on September 18, 2022Comments
-
GP92 over 1 year
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.
-
Stéphane Chazelas about 9 yearsThat command crashed my machine. I had a
AB.\(a*\)\{10000\}-DEF
file in the current directory. -
nghnam about 9 yearsI edited my post, quoted the search pattern. Thank you.
-
cuonglm about 9 years@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.
-
heemayl about 9 yearsThis will match many other patterns e.g.
ABCGLHHJKH90-DEF
-
Eric Renouf about 9 yearsTrue heemayl, but it is in keeping with the filesystem glob expansion like Jeevan seemed to be trying for in the question.