Using the star sign in grep Ask Question

Using the star sign in grep Ask Question

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?

ベストアンサー1

For such two-part matches, use .* between the two parts.

For instance:

grep 'abc.*def' myFile

will match a string that contains abc followed by def with something optionally in between.


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.

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.

おすすめ記事