Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grep with special characters

Tags:

string

regex

r

I want to find the elements that contains star character in the following vector.

s <- c("A","B","C*","D","E*")
grep("*",s)

[1] 1 2 3 4 5

This is not working. I can understand that since it is a special character.
When I read here, I decided to use "\" before star character. But that gave me an error:

grep("\*",s)
Error: '\*' is an unrecognized escape in character string starting ""\*"

What am I doing wrong?

like image 476
HBat Avatar asked Jul 02 '13 20:07

HBat


People also ask

How do you use special characters in grep?

If you include special characters in patterns typed on the command line, escape them by enclosing them in single quotation marks to prevent inadvertent misinterpretation by the shell or command interpreter. To match a character that is special to grep –E, put a backslash ( \ ) in front of the character.

How do I ignore special characters in grep?

5 Searching for Metacharacters. Suppose you want to find lines in the text that have a dollar sign ( $ ) in them. Preceding the dollar sign in the regular expression with a backslash ( \ ) tells grep to ignore (escape) its special meaning.

Can I use * in grep command?

Grep can identify the text lines in it and decide further to apply different actions which include recursive function or inverse the search and display the line number as output etc. Special characters are the regular expressions used in commands to perform several actions like #, %, *, &, $, @, etc.

Does grep work with wildcards?

The wildcard * (asterisk) can be a substitute for any number of letters, numbers, or characters. Note that the asterisk (*) works differently in grep. In grep the asterisk only matches multiples of the preceding character. The wildcard * can be a substitute for any number of letters, numbers, or characters.


1 Answers

You need to escape special characters twice, once for R and once for the regular expression:

grep('\\*', s)
like image 162
Justin Avatar answered Sep 28 '22 05:09

Justin