Example input:

void C::foo()
{ // <- this changes bracket balance from 0 to 1
    if (true)
    { // balance is 2 after we process this bracket
    } // now it is 1 again
} // now bracket balance is zero again, so next opening brace will be 
  // subsituted


void C::foo()
    if (true)

I have sed and awk at my disposal. Currently I know how to do the substitution in a very generic way thanks to the answer here How to edit a multiline pattern in bash (sed and awk are available), but I do not know how to catch the described curly braces.

awk -F "" '{
   for (i=1;i<=NF;i++) {
      if ($i == "}" && count > 0) count--
      if ($i == "{" ) if (count++ == 0) $i="{ PROCESSED;"
      printf "%s", $i
   printf "%s", ORS

I used this approach to parse each line character by character.


  • The logic does not allow count to reach negative values.
  • (count++ == 0) increases the count after comparing to 0.
  • ORS is the output record separator, by default a newline.
  • The code doesn't care about quoting, escaping, comments etc.
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.