tags:

views:

414

answers:

3

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.

+2  A: 

Try a character class instead

echo "$STRING" | egrep '[*]'
pavium
A: 

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 "*"
$
Mark Rushakoff
Your 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!
DaveParillo
@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, use `fgrep` instead.
Gordon Davisson
A: 

Use:

grep "*" file.txt

or

cat file.txt | grep "*"
DaveParillo
since you can do the first, the second one with cat is not necessary.
ghostdog74
I 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