In a file I have multiple if conditions like below:

if ( a==b ||
c!=d &&
(e>f))
{
do something
}

I have to convert each multiline if statement to single line if statement i.e

if ( a==b || c!=d && (e>f))
{
do something
}

How can I do this conversion using Unix scripting?

closed as off-topic by Patrick, Stephen Rauch, xhienne, Kusalananda, devWeek Aug 20 '17 at 16:50

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question has been posted on multiple sites. Cross-posting is strongly discouraged; see the help center and community FAQ for more information." – Patrick, Stephen Rauch, xhienne, Kusalananda, devWeek

Run it through an indentation tool such as indent or clang-format. These know the C and C++ grammar rules and will reformat your code according to how you configure them. clang-format is even using the same language parser as the clang compiler.

For example:

$ cat test.c
if ( a==b ||
c!=d &&
(e>f))
{
/* do something */
}

$ clang-format test.c
if (a == b || c != d && (e > f)) {
  /* do something */
}

$ clang-format --style="{BreakBeforeBraces: Allman}" test.c
if (a == b || c != d && (e > f))
{
  /* do something */
}

$ indent -kr -st <test.c
if (a == b || c != d && (e > f)) {
/* do something */
}

$ indent -kr -bl -st < test.c
if (a == b || c != d && (e > f))
{
/* do something */
}

The indent used in the example above is GNU indent, not the default indent found on BSD systems.

  • Thanks. Is there any logic for this or any other solution apart from using predefined tools? – Ayush Malik Aug 20 '17 at 10:23
  • The logic is that it's difficult to write a shell script that flawlessly parses C or C++ syntax, and since there already are well tested tools that does exactly what you want to do, you ought to use these instead of trying to write a C language parser yourself. – Kusalananda Aug 20 '17 at 10:28

Could be done with awk:

awk '(/^\{/ || flag)&&/^[^}]/{printf "\n%s",$0;flag=1} 
      /^\}/{flag=0; printf "\n}\n" ;next} 
     (!flag){printf "%s ",$0}' infile.txt

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