I have many java source files in which I want to change a code block to another code block in every java files that I have in my project.
e.g. My project has about 300 java source file and every 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 code block to
while (p.nextToken() != null) {
field = p.getCurrentName();
if(field!=null){
obj.populateFromJsonString(field, p);
}
}
in all the java files. object obj in code block is different for different files
I know somehow this can be done by text processing with sed and awk. I am thinking for alternate solution the way compilers read and parse java source file. there may be some application based on this way for solving my problem.
Please share way or application to solve this problem. sed/awk based solutions are also welcome.
It's probably best to use an IDE to do this, but if you really wanted to use sed, put this 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 in the command line
find . -type f -name '*.java' -exec sed -i.bak -f j.sed {} \;
This will on 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);
}
}
The -i.bak will edit in place and store a backup as filename.java.bak
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With