Reputation: 1982
I have the following text in multiple files Hello{Some Text}
, and I want to replace it with Some Text
. Where Some Text
might include balanced braces { }
. For example: Hello{Some { other} Text}
should be replaced by Some { other} Text
.
Is there an easy way to achieve this in sed
, awk
, perl
or some other tool?
Upvotes: 1
Views: 76
Reputation: 48751
You have to choose perl
since it supports sub-routine calls. A recursive match on {[^{}]*}
should occur continuously and should fail if an unbalanced brace is found. Below regex does the job:
Hello({((?:[^{}]*+|(?1))*)})
See live demo here
Note: it fails on facing with escaped braces.
Perl:
$ echo 'Hello{Some { other} Text}' | perl -pe 's~Hello({((?:[^{}]*+|(?1))*)})~$2~g'
Some { other} Text
Regex breakdown:
Hello # Match `Hello`
( # Start of 1st capturing group
{ # Match `{`
( # Start of 2nd capturing group
(?: # Start of non-capturing group
[^{}]*+ # Match anything but `{` or `}` possessively
| # Or
(?1) # Recurs first group
)* # End of NCG, repeat as much as possible
) # End of 2nd CP
} # Match `}`
) # End of 1st CP
Upvotes: 3