sed one-liner to delete everything between a pair of brackets?

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?


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

The command sed -e 's/([^()]*)//g'will do parentheses instead of brackets.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x