When using grep on the command line I am getting different results when I use a %
percent symbol.
I expect this expression to match it returns nothing:
bash-4.1$ echo ' (in=Gen)' | grep -in '*(*)'
However if I include a leading percentage character it's a match:
bash-4.1$ echo ' (in=Gen)' | grep -in '%*(*)'
1: (in=Gen)
Is the percent %
symbol a special or control character in grep? Looking at the available documentation I don't see any reference to it.
If you put any other (valid) character, there would be a match too eg using ,
:
% echo ' (in=Gen)' | grep -in ',*(*)'
1: (in=Gen)
The problem is with your pattern, *(*)
, here:
*
means to match zero or more of the preceding token, as there is no preceding token it matches *
literally. As there is no *
present, the pattern does not match anything While in %*(*)
:
%*
means to match %
zero or more times, as there is no %
present, grep
matches nothing for %*
; in this case grep
only matches the last )
In BRE (Basic regular expressions) that grep
uses (as opposed to ERE, extended REs from egrep
or grep -E
, if a *
is nor a quantifier of a preceding expression, it will match the literal star. (This also happens with a ^
that is not at the beginning of an expression, and a $
that is not in a position to match end of line: They are interpreted as the normal characters ^
and $
.
From man 7 regex
:
'^' is an ordinary character except at the beginning of the RE or(!) the beginning of a parenthesized subexpression, '$' is an ordinary character except at the end of the RE or(!) the end of a parenthesized subexpression, and '*' is an ordinary character if it appears at the beginning of the RE or the beginning of a parenthesized subexpression (after a possible leading '^').
As to your second example, what is only matched is the closing bracket (marked with a ^
on top):
^
echo ' (in=Gen)' | grep --color -in '%*(*)'
1: (in=Gen)
Notice the use of --color
to grep
to highlight what actually is matched, this has been pretty invaluable to understand grep's behavior).
The seach you are looking for, is likely this one:
% echo '*(in=Gen)' | grep -in --color '*(.*)'
1:*(in=Gen)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.