Why am I getting the error "missing terminating ] for character class"?
7,810
Solution 1
As the error missing terminating ] for character class already says, the problem here has to do with [
, which you need to escape. Otherwise, it is understood as a character class by grep.
Also, you are saying //
, while you want to use /
instead of \
according to your input.
All together, this prints a set of words after [Om/
:
$ echo '[Om/mystring' | grep -oP '(?<=\[Om\/)\w+'
mystring
Solution 2
You are getting the error because [
is a special character in regular expression syntax, introducing a character class. To be treated as a string literal, it must be escaped i.e. \[
If you just want to remove the [Om/
prefix, then it's simpler sed if you use a delimiter that doesn't appear in the pattern:
$ echo '[Om/mystring' | sed 's;\[Om/;;'
mystring
Related videos on Youtube
Author by
Josef Klimuk
Updated on September 18, 2022Comments
-
Josef Klimuk over 1 year
I want to cut a string with brackets using
sed
.How to avoid an error if I want to drop a string with
[
? For example:$ echo '[Om/mystring' | grep -oP '(?<=[Om\\)\w+' grep: missing terminating ] for character class
-
fedorqui about 6 yearsYou can also add the anchor
^
to make it match just the beginning of the line. -
Uyghur Lives Matter about 6 yearsI don't think the "g" in "\grep" needs to be escaped.
-
JoL about 6 years@cpburnz that's a trick to avoid it being interpreted as a shell alias. I imagine he did it to avoid his own alias, while testing this in the shell.