简体   繁体   中英

AWK Regex to find specific patterns

I have many java files in a project and there are few loops which are empty and there are few loops which have some logic in it. I need to find the loops which does not have any logic in it.

For example: Name this file as Test.java

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 there will lot of other java files like this, where while loop would have been used. I need to find all the files where the while loop without any logic is there. So I need to write a pattern where I can find occurances of all the while loops which does not have any logic or any content between the { } braces.

If we take this file (Test.java) then I should get the output as :

   while (x <5)
   {

   }

with the file name and the line number. As there will be lot of files to refer I need file name and the line number where this occurance is happening.

Hope I am clear with my question.

Please help.

Never use range expressions as they make trivial tasks very slightly briefer but need a complete rewrite or duplicate conditions for even the slightest requirements change, as you just discovered. Always set/test a flag instead.

You cannot do this job robustly without a parser for the language, eg what would you do if there was a comment or a string or an if { ... } or anything else even slightly interesting inside your populated while loop?

You also didn't provide any real sample input/output to test a solution against, nor do you tell us what you want to do when you find what you're looking for - print it? remove it? something else?

Having said all of that, this cheap and cheerful "solution" might be good enough for your needs:

awk '
inWhile && /}/ { 
    if (!gotStuff) {
        print "Empty loop ended at line", NR
    }
    inWhile=0
}
inWhile && NF { gotStuff=1 }
/while\s*\([^)]*\)\s*{/ { inWhile=1; gotStuff=0 }
' file

The above uses \\s shorthand for [[:space:]] , just don't use that shorthand if your awk doesn't support it (GNU awk does).

If the above isn't adequate edit your question to provide some concrete, testable, sample input and expected output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM