Bash – Using sed to remove both an opening and closing square bracket around a string

bashregexsed

I'm running this command in a bash shell on Ubuntu 12.04.1 LTS. I'm attempting to remove both the [ and ] characters in one fell swoop, i.e. without having to pipe to sed a second time.

I know square brackets have special meaning in a regex so I'm escaping them by prepending with a backslash. The result I was expecting is just the string 123 but the square brackets remain and I'd love to know why!

~$ echo '[123]' | sed 's/[\[\]]//'
[123]

Best Answer

This is easy, if you follow the manual carefully: all members inside a character class lose special meaning (with a few exceptions). And ] loses its special meaning if it is placed first in the list. Try:

$ echo '[123]' | sed 's/[][]//g'
123
$

This says:

  1. inside the outer [ brackets ], replace any of the included characters, namely:
    • ] and
    • [
  2. replace any of them by the empty string — hence the empty replacement string //,
  3. replace them everywhere (globally) — hence the final g.

Again, ] must be first in the class whenever it is included.

Related Topic