Java – only remove system. Java from the for loops block Out statement
Any method can only easily delete them from the for loop blocks in the file
Before:
for( ... ) { ... System.out.println("string"); ... System.out.println("string"); ... }
After:
for( ... ) { ... ... ... }
Solution
This is tricky: which closing bracket closes for loop? Either parse the entire code or use some heuristics In the following solution, I require that the intention of the right parenthesis is the same as that of the for keyword:
$perl -nE' if( /^(\s*)for\b/ .. /^$ws\}/ ) { $ws = $1 // $ws; /^\s*System\.out\.println/ or print; } else { print }'
This uses the trigger operator cond1 COND2. This script can be used as a simple filter
$perl -nE'...' <source >processed
Or backup function:
$perl -i.bak -nE'...' source
(create the file source.bak as a backup)
Test only for example inputs; Not a sensible test suite The script passed the gles prateek Nina test
To run this script on all java files in the directory
$perl -i.bak -nE'...' *.java
edit
On Windows systems, the delimiter must be changed to ". In addition, we must perform global operations ourselves
> perl -nE"if(/^(\s*)for\b/../^$ws\}/){$ws=$1//$ws;/^\s*System\.out\.println/ or print}else{print}BEGIN{@ARGV=$#ARGV?@ARGV:glob$ARGV[0]}" *.java
Edit 2
This is the implementation of the bracket counting algorithm outlined in my review This solution can also be backed up Command line arguments are interpreted as glob expressions
#!/usr/bin/perl use strict; use warnings; clean($_) for map glob($_),@ARGV; sub clean { local @ARGV = @_; local $^I = ".bak"; my $depth = 0; while (<>) { $depth ||= /^\s*for\b/ ? "0 but true" : 0; my $delta = ( ()= /\{/g ) - ( ()= /\}/g ); $depth += $delta if $depth && $delta; $depth = 0 if $depth < 0; print unless $depth && /^\s*System\.out\.println/; } return !!1; }
There is no comment This will only re identify the system that started the new line out. Println statement
Usage example: > Perl thisscript pl * . java.
This is a test file with pseudo Java syntax. I use it to test Once the script runs, all lines marked XXX will disappear
/** Java test suite **/ bare block { System.out.println(...); // 1 -- let stand } if (true) { for (foo in bar) { System.out.println; // 2 XXX if (x == y) { // plz kill this System.out.println // 3 XXX } // don't exit here System.out.println // 4 XXX } } for (...) { for { // will this be removed? System.out.println // 5 XXX } } /* pathological cases */ // intendation for (...) { System.out.println()/* 6 */} // intendation 2 for (...) { if (x) { System.out.println // 7 XXX }} // inline weirdness for (...) { // "confuse" script here foo = new baz() {void qux () {...} }; System.out.println // 8 XXX }
No. 1 should stay, and it is Declaration № 6 shall be deleted; But these scripts can't do that