How to replace a Java code block with another code block automatically or pragmatically?

I have a lot of java source files where I want to change the code block to a different code block in every java file I have in my project.

eg. My project has about 300 java source files and each file has this code block

while (p.getCurrentToken() != JsonToken.END_OBJECT) {
    p.nextToken();
    field = p.getCurrentName();
    obj.populateFromJsonString(field, p);
} 

      

I want to replace this block of code with

while (p.nextToken() != null) {
    field = p.getCurrentName();
    if(field!=null){
        obj.populateFromJsonString(field, p);
    }
}

      

in all java files. the object obj

in the code block is different for different files

I know it can be done with text processing with sed and awk . I am thinking of an alternative solution, how compilers read and parse a java source file. there might be some application based on this path to solve my problem.

Please share a method or application to solve this problem. Sed / awk based solutions are also welcome.

+3


source to share


2 answers


It's probably best to use an IDE for this, but if you really wanted to use sed, put it in a file called j.sed

/while (p\.getCurrentToken() != JsonToken\.END_OBJECT) {/{
    :loop
    n
    /}/b    
    s/field = p\.getCurrentName();/if (field!=null) {/
    s/p\.nextToken();/field = p\.getCurrentName();/
    s/...\.populateFromJsonString(field, p);/\t&\n\t}/
    b loop
}

      

Then use on the command line

find . -type f -name '*.java' -exec sed -i.bak -f j.sed {} \;

      

This will be at the input:



while (p.getCurrentToken() != JsonToken.END_OBJECT) {
    p.nextToken();
    field = p.getCurrentName();
    obj.populateFromJsonString(field, p);
} 

      

Output this:

while (p.getCurrentToken() != JsonToken.END_OBJECT) {
    field = p.getCurrentName();
    if (field!=null) {
        obj.populateFromJsonString(field, p);
    }
} 

      

-i.bak will edit in place and store the backup as filename.java.bak

+1


source


How about this

$ searchvar=`cat searchblock.txt`  
$ replvar=`cat replblock.txt`  

$ sed -i ":loop; $! N; tloop;  s/$searchvar/$replvar/g" *.java

      

where in searchblock.txt

you add the input block so *.java

you catch all the java files in the folder



notification `

not'

Be careful when testing for -i

inplace editing , you can try with backup files

-2


source







All Articles