Why am I getting the error "missing terminating ] for character class"?

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

2 Answers

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
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
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like