Remove bracket including text inside with sed

Hello,

I could not remove brackets with text contents

myfile:

Please remove the bracket with text [A1]

I wish to remove: [A1]

I tried:

sed 's/\[//;s/\]//'  myfile

It gives:

Please remove the bracket with text A1

I expect:

Please remove the bracket with text

Many thanks
Boris

echo 'Please remove the bracket with text [A1]' | sed 's/\[[^]]*\]//'
1 Like

vgersh99 already answered your question but you might want to know why your code didn't work:

Well, s/\[// replaces an opening bracket with nothing (effectively deleting it) and the other substitution does the same with closing brackets. This is why only the brackets are removed, but not what they enclose.

vgersh99s code searches for an opening bracket, followed by any number of not-closing-bracket-characters, followed by a closing bracket and removes this.

I hope this helps.

bakunin

1 Like