22

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?

2 Answers 2

28

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.

5
  • thanks, @Gilles... btw, it can span multiple lines, but I'm using a Perl script to join lines...
    – ixtmixilix
    Jun 12, 2011 at 11:25
  • @ixtmixilix: If you have a Perl script, you can make it remove the bracketed text as well. In Perl, you can write s/\[[^\[\]]*\]//g (i.e. use backslashes to escape the members of the character set). Jun 12, 2011 at 11:58
  • @Gilles could you explain more about [^][] exactly plz. thank you
    – Arash
    May 17, 2013 at 17:23
  • 1
    @arashams […] = character set. ^ as the first character means to complement the set. ] would normally be mark the end of the set, but if it's the first character other than ^, it's an ordinary character — an empty set or the complement of the empty set isn't permitted. Then [ is ordinary and ] ends the set. May 17, 2013 at 18:35
  • @Gilles tnx for your help but still i dont get it :( what dose that mean? "^ as the first character means to complement the set" i mean what is it doing ? for example is it matched to all contents?
    – Arash
    May 17, 2013 at 20:01
11

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .