There are many threads on find replace text for python but I think my question is different.
I have a bunch of java files with
System.out.println("some text here");
I am trying to write a python script which will replace them all with
if (logger.isInfoEnabled()) {
logger.info("some text here");
}
To do this I have tried:
def findReplace(fileName, sourceText, replaceText):
file = open(fileName, "r") #Opens the file in read-mode
text = file.read() #Reads the file and assigns the value to a variable
file.close() #Closes the file (read session)
file = open(fileName, "w") #Opens the file again, this time in write-mode
file.write(text.replace(sourceText, replaceText)) #replaces all instances of our keyword
# and writes the whole output when done, wiping over the old contents of the file
file.close() #Closes the file (write session)
and pass in:
filename=Myfile.java, sourceText='System.out.println', replaceText='if (logger.isInfoEnabled()) { \n' \logger.info'
However, I am struggling to the get the closing ' in the replace. It needs to wrap out around the same output string that is already there. Any tips?
Thanks.
import re
sourceText = 'System\.out\.println\(("[^"]+")\);'
replaceText = \
r'''if (logger.isInfoEnabled()) {
logger.info(\1);
}'''
re.sub(sourceText, replaceText, open(fileName).read())
This isn't perfect -- it will only work if the string doesn't contain any escaped quote marks i.e. \" -- but hopefully it should do the trick.
You will certainly have trouble with that, because doing replacements around matching delimiters is hard. One approach that makes way more sense to me -- for more reasons than one -- is to define a new java function log_if_enabled, and then just replace System.out.println with log_if_enabled. That way, you don't have to worry about doing any fancy brace matching. Also, encapsulating the if statement in a function is DRY.
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