Grep/ AWK match multiple lines

139 views Asked by At

Hi I have a java file,

public class Test {

 public static void main(String args[]) {
  int x = 10;

 while( x < 5)
 {
 }
  while( x < 20 ) {
   System.out.print("value of x : " + x );
   x++;
   System.out.print("\n");
  }
}
 }

Now as you can see there are two while loops , one while loop is empty and other while loop has got some logic.

Now I would like to print the while loop which has got no logic in it. In other words I would like to grep and print the while loop which does not have any logic. How can I grep Multiple lines. So that I can print the while loop which has no logic.

I have tried this:

gawk '/while\s*\(\S*\)[[:space:]]*{[[:space:]]*/,/}$/' *.java

But it does not match.

1

There are 1 answers

0
ShellFish On

Do something like this using , in pseudo code:

# get lines where loop starts
/(for|while)[ \t]*([^)]*)/ {
    # save loop signature
    loops[++i] = $0
    while ($0 !~ /{/)
        getline
    getline
    # store number of open braces
    open=1
}
# when in loop count braces to see when we leave scope
open > 0 {
    if ($0 ~ /{/) 
        open++
    if ($0 ~ /}/)
        open--
    # if line is not a comment or empty, loop not empty
    if ($0 !~ [ \t]*((\/\/|\*).*)?)
        delete loops[i--]
}
END {
    for (j=1; j<i; j++)
        printf loops[j] "\n{\n}\n"
}

Note that this is pseudo code (read untested and incomplete), to give you an idea how to achieve the goal. You can try it out and comment when running into trouble. Note also that for nested loops the strategy will become a little more difficult but it's easy to bypass that problem (hint: the outer loop contains a loop so you can forget about the outer loop when running into an inner loop since it is not empty).