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

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

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest