Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grep asterisk without escaping?

Suppose I have a file abc.txt which contains line ab*cd. When I grep that pattern ab*cd with quotes but without escaping the asterisk it does not work:

> grep ab*c abc.txt 
> grep "ab*c" abc.txt 
> grep 'ab*c' abc.txt 

When I use both quotes and escaping it does work

> grep "ab\*c" abc.txt 
ab*cd
> grep 'ab\*c' abc.txt 
ab*cd

Now I wonder why the quotes do not work and if I can use only quotes without escaping the asterisk.

like image 390
Michael Avatar asked Aug 12 '13 16:08

Michael


People also ask

How do you grep with asterisk?

When an asterisk ( * ) follows a character, grep interprets it as "zero or more instances of that character." When the asterisk follows a regular expression, grep interprets it as "zero or more instances of characters matching the pattern." You may want to try this to see what happens otherwise.

How do you escape asterisk in grep?

If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.

What does asterisk mean in grep?

There is a difference between normal shell file name patterns (called glob) where * matches any number of unknown characters, and regular expressions that are used for example by grep , where * stands for zero or more occurences of the previous pattern (this is the character a in your example).


2 Answers

Use the flag -F to search for fixed strings -- instead of regular expressions. From man grep:

   -F, --fixed-strings
          Interpret  PATTERN  as  a  list  of  fixed strings, separated by
          newlines, any of which is to be matched.  (-F  is  specified  by
          POSIX.)

For example:

$ grep -F "ab*c" <<< "ab*c"
ab*c
like image 80
Rubens Avatar answered Oct 20 '22 00:10

Rubens


first of all, you should keep in mind: regex =/= glob

* has special meaning in regex. You have to escape it to match it literally. without escaping the *, grep tries to match ab+(any number of b)+c

for example:

abbbbbbbbbbbbc

like image 43
Kent Avatar answered Oct 19 '22 23:10

Kent