Sed – One-Liner to Delete Everything Between Brackets

regular expressionsed

I am working with some text that is full of stuff between brackets [] that I don't want. Since I can delete the brackets myself, I don't need the one-liner to do that for me, but I do need a one-liner that will remove everything between them.

What about parentheses () instead of brackets?

Best Answer

Replace [some text] by the empty string. Assuming you don't want to parse nested brackets, the some text can't contain any brackets.

sed -e 's/\[[^][]*\]//g'

Note that in the bracket expression [^][] to match anything but [ or ], the ] must come first. Normally a ] would end the character set, but if it's the first character in the set (here, after the ^ complementation character), the ] stands for itself.

If you do want to parse nested brackets, or if the bracketed text can span multiple lines, sed isn't the right tool.

Related Question