matching a line with a literal asterisk "*" in grep
39,365
Solution 1
Try a character class instead
echo "$STRING" | egrep '[*]'
Solution 2
echo "$STRING" | fgrep '*'
fgrep
is used to match the special characters.
Solution 3
Simply escape the asterisk with a backslash:
grep "\*"
Solution 4
Use:
grep "*" file.txt
or
cat file.txt | grep "*"
Solution 5
Here's one way to match a literal asterisk:
$ echo "*" | grep "[*]"
*
$ echo "*" | egrep "[*]"
*
$ echo "asfd" | egrep "[*]"
$ echo "asfd" | grep "[*]"
$
Wrapping an expression in brackets usually allows you to capture a single special character easily; this will also work for a right bracket or a hyphen, for instance.
Be careful when this isn't in a bracket grouping:
$ echo "hi" | egrep "*"
hi
$ echo "hi" | grep "*"
$
Related videos on Youtube
Author by
Derrick
Updated on July 09, 2022Comments
-
Derrick almost 2 years
Tried
$ echo "$STRING" | egrep "(\*)"
and also
$ echo "$STRING" | egrep '(\*)'
and countless other variations. I just want to match a line that contains a literal asterisk anywhere in the line.
-
Daren Schwenke over 14 yearsI usually just keep adding slashes until I get what I want. :)
-
Gordon Davisson over 14 yearsBoth of your examples work for me (and also work with the parentheses removed).
-
-
ghostdog74 over 14 yearssince you can do the first, the second one with cat is not necessary.
-
DaveParillo over 14 yearsI hear ya. Many people seem to like using cat to stream a file into all sorts of programs even though it's typically redundant. I just thought I'd include it to make the example look more familiar.
-
DaveParillo over 14 yearsYour example shows why I find this behavior of egrep irritating. If you want to do a literal string search with grep, just put it in quotes. Why would I ever want to grep for everything? unix calls that program 'cat' ;-) I hate the egrep forces you to bracket regex characters even if they are in double quotes. End of rant. Thanks!
-
Gordon Davisson over 14 years@DaveParillo: neither grep nor egrep know whether the pattern you passed them was quoted or not, as the quotes are interpreted by the shell before [e]grep is launched. The difference is due to how grep and egrep respond when the pattern starts with "", which is technically malformed ("" is a suffix). Try
grep ".*"
and you'll see that it matches everything. If you want a literal (non-regex) search, usefgrep
instead. -
Brian Burns almost 11 yearsOn Windows with GnuWin32, you can use
grep [*] file.txt
. -
tripleee over 7 years... except if you have a file named literally
*
in the directory where you run that. The lesson (not particularly from this example, but generally) is to always quote your regular expressions, no matter how trivial.