Escaping close-bracket character in grep complement
grep, regex
Solution
How do I escape a close-bracket character inside a character class?
A `]` is normally either the end of a POSIX character class, or it signals the end of the character class.
If a `]` is the first character in the class (may follow an unescaped caret) it does not denote the end of the class and is evaluated as part of the set of characters that can be matched without escaping.
echo "foo [22-Jun-2014 04:11:37 UTC] bar" | grep -o '\[[^]]*\]'
# [22-Jun-2014 04:11:37 UTC]
Problem
How do I escape a close-bracket character inside a character class? According to the manual, to match a literal ] it should be placed first in the list, but I need to match the complement of a class consisting of square bracket. Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last.