Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape square closing bracket in sed [duplicate]

Tags:

regex

bash

sed

I'm parsing come legacy C-code using grep and sed and when trying to replace square brackets, something strange happened.

The following code to replace square opening brackets works fine:

$ echo "xyx[xzx]xyx" | sed 's|[\[]| |g'

results in:

xyx xzx]xyx

When I now add \] to the string to sed, to also replace square closing brackets, it stops working:

$ echo "xyx[xzx]xyx" | sed 's|[\[\]]| |g'

now results in:

xyx[xzx]xyx

As far as I know, this is the proper way to escape square brackets.

What am I doing wrong?

I'm running this on a Ubuntu 14.04 machine.

like image 312
NZD Avatar asked Jan 15 '15 21:01

NZD


Video Answer


1 Answers

You don't even need to escape:

echo "xyx[xzx]xyx" | sed 's|[][]| |g'
xyx xzx xyx

However keep in mind that order of ] then [ is important here.

like image 162
anubhava Avatar answered Nov 16 '22 03:11

anubhava