I am aware that pattern [abc] matches a single character that is either a or b or c in the regular expressions, but how can I match for either [ or ]? I don't know how to escape them properly.


The pattern to use is [][]. Take GNU grep as an example. All of the following three will do.

grep '[][]' file
grep -P '[][]' file
grep -E '[][]' file

Explanation: The bracket expression in regular expression cannot have an empty body (Try grep '[]' file and an error will be reported), so the first [ actually goes with the last ]. The [ inside the pair of brackets does not interfere because bracket expression cannot be nested, so once a [ is seen, the RE engine will look for the first ] starting from the 2nd character after it as the closing ]. Inside a bracket expression, only [:class:] [.coll.] [=equiv=] and c-c ranges, together with the ^ that appears at the beginning are treated specially, other characters are treated literally with no need for escaping (see comment by @dave_thompson_085 for link to manual pages).

  • As stated in the manual "... if you want to make the ‘]’ character a list item, you must put it first". But [:class:] [.coll.] [=equiv=] and c-c ranges and initial ^ are NOT literal in a bracket expression. All the cases with [ are handled by putting it at the end, - is handled by putting it at the end or the beginning (modulo ^ if used), and ^ by putting it not at the beginning. – dave_thompson_085 May 2 at 8:28
  • Thank you for your correction. I will update the answer. – Weijun Zhou May 2 at 8:32
  • That's different in perl/PCRE regexps (and the EREs of many awk implementations, also GNU sed without POSIXLY_CORRECT, vim with nocompatible...), where one can use [\[\]] (i.e. backslash is also special inside bracket expressions). Or IOW, if you also want backslash to be included in that list portable, you'd need [][\\] (double the backslash). – Stéphane Chazelas May 2 at 8:53
  • Can you expand it to an answer? I will accept it. – Weijun Zhou May 2 at 9:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.