How to Grep for Strings with Special Characters Like []

grep for special characters in Unix

Tell grep to treat your input as fixed string using -F option.

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

Option -n is required to get the line number,

grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log

How do I grep for strings with special characters like []?

You are right that [ and ] are special characters. Quote them with \ or use fgrep instead. The latter is plain string search:

fgrep "\$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']" ...

You still need to quote $ though because it is otherwise interpreted by bash and other shells.

How to use grep to get special character

grep -F 'special char' filename will search the lines which has special characters.

grep -Fn 'special char' filename gets the line number too.

man grep says,
-F, --fixed-strings: Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched

grepping special characters in R

By plugging this regex into https://regexr.com/ I was able to spot the issue: if you have - in a character class, you will create a range. The range from ' to _ happens to include uppercase letters, so you get spurious matches.

To avoid this behaviour, you can put - first in the character class, which is how you signal you want to actually match - and not a range:

> grepl("[-?.,;:'_+=()!@#$%^&*|~`{}]", full.path)
[1] FALSE

How to make grep not interpret special characters in my search string?

You could use grep with the -F option:

From man grep:

 -F, --fixed-strings
Interpret pattern as a set of fixed strings (i.e. force grep to
behave as fgrep).

Your example:

grep -F "$ip"

Using grep to search for a string that has a dot in it

grep uses regexes; . means "any character" in a regex. If you want a literal string, use grep -F, fgrep, or escape the . to \..

Don't forget to wrap your string in double quotes. Or else you should use \\.

So, your command would need to be:

grep -r "0\.49" *

or

grep -r 0\\.49 *

or

grep -Fr 0.49 *

How do I git grep for a string including a ?

When doubt, use a single-character class rather than a backslash to make a single character literal inside a regex:

git grep -e '-[>]upload'

Whereas the meaning of a backslash can be different depending on the specific character and the specific regex syntax in use, [>] means the same thing consistently.

That said, the most immediate issue here isn't caused by the > but by the leading dash, which makes the string indistinguishable from a list of options.

The -e is needed not because of the >, but because of the -. Without it, ->upload would be treated as a series of flags (->, -u, -p, -l, -o, -a, -d).


That said, you can get away without the -e by also moving the dash into a character class, thus making it no longer the first character on the command line:

git grep '[-][>]upload'


Related Topics



Leave a reply



Submit