Remove redundant braces from code

324 views Asked by At

I am trying to use tr command or any similar command to perform a specific text manipulation to this block:

if (/*condition*/)
{
    statement1;
}
int a=3;
if (a)
{
    statement1;
    statement2;
}
else
{
    statement1;
    statement2;
    statement3;
    statement4;
    ///may be more lines
}

I want to remove single line commands and get this:

if (/*condition*/)
    statement1;
int a=3;
if (a)
{
    statement1;
    statement2;
}
else
{
    statement1;
    statement2;
    statement3;
    statement4;
    ///may be more lines
}

I've tried tr -s '{}' ' ' <file.txt but it squeezes all of the braces, not with the specific single line format.

Thanks

1

There are 1 answers

4
fedorqui On

You can set the record separator to either { or } and check how many fields you have. If there are more than one, print brackets around:

$ awk -v RS=[{}] 'NF>1{$0="{"$0"}"}1' file
if(true)


statement;


if(false)

{
statement1;
statement2;
}