开发者

matching a line with a literal asterisk "*" in grep

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 anywh开发者_Go百科ere in the line.


Try a character class instead

echo "$STRING" | egrep '[*]' 


echo "$STRING" | fgrep '*'

fgrep is used to match the special characters.


Use:

grep "*" file.txt

or

cat file.txt | grep "*"


Simply escape the asterisk with a backslash:

grep "\*"


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 "*"
$


If there is a need to detect an asterisk in awk, you can either use

awk '/\*/' file

Here, * is used in a regex, and thus, must be escaped since an unescaped * is a quantifier that means "zero or more occurrences". Once it is escaped, it no longer has any special meaning.

Alternatively, if you do not need to check for anything else, it makes sense to peform a fixed string check:

awk 'index($0, "*")' file

If * is found anywhere inside a "record" (i.e. a line) the current line will get printed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜