Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the star sign in grep

Tags:

regex

grep

bash

I am trying to search for the substring "abc" in a specific file in linux/bash

So I do:

grep '*abc*' myFile 

It returns nothing.

But if I do:

grep 'abc' myFile 

It returns matches correctly.

Now, this is not a problem for me. But what if I want to grep for a more complex string, say

*abc * def * 

How would I accomplish it using grep?

like image 450
Saobi Avatar asked Jul 01 '09 14:07

Saobi


People also ask

How do you grep a star?

When an asterisk ( * ) follows a character, grep interprets the asterisk as “zero or more instances of that character.” When the asterisk follows a regular expression, grep interprets the asterisk as “zero or more instances of characters matching the pattern.”

Can I use * in grep command?

Search All Files in Directory To search all files in the current directory, use an asterisk instead of a filename at the end of a grep command. The output shows the name of the file with nix and returns the entire line.

How do you grep special characters?

To match a character that is special to grep –E, put a backslash ( \ ) in front of the character. It is usually simpler to use grep –F when you don't need special pattern matching.

Can you use wildcards with grep?

Wildcards. If you want to display lines containing the literal dot character, use the -F option to grep.


1 Answers

The asterisk is just a repetition operator, but you need to tell it what you repeat. /*abc*/ matches a string containing ab and zero or more c's (because the second * is on the c; the first is meaningless because there's nothing for it to repeat). If you want to match anything, you need to say .* -- the dot means any character (within certain guidelines). If you want to just match abc, you could just say grep 'abc' myFile. For your more complex match, you need to use .* -- grep 'abc.*def' myFile will match a string that contains abc followed by def with something optionally in between.

Update based on a comment:

* in a regular expression is not exactly the same as * in the console. In the console, * is part of a glob construct, and just acts as a wildcard (for instance ls *.log will list all files that end in .log). However, in regular expressions, * is a modifier, meaning that it only applies to the character or group preceding it. If you want * in regular expressions to act as a wildcard, you need to use .* as previously mentioned -- the dot is a wildcard character, and the star, when modifying the dot, means find one or more dot; ie. find one or more of any character.

like image 147
Daniel Vandersluis Avatar answered Sep 20 '22 07:09

Daniel Vandersluis