Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find line, replace multiple lines

Tags:

python

text

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.

like image 487
dublintech Avatar asked May 14 '26 05:05

dublintech


2 Answers

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.

like image 197
bluepnume Avatar answered May 16 '26 17:05

bluepnume


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.

like image 43
senderle Avatar answered May 16 '26 19:05

senderle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!