I came across a need to replace the string in existing file using Jython during developing a Weblogic script to automate Domain Setup. I need to replace certain values in files after domain gets created. Below example illustrates how we can do using Jython. It may not be best way to do but does the job what is expected.

Following Jython script replaceLines.py will replace string in exiting file.


import sys
import os

def replaceAll(fileName, oldStr, newStr):
	srcFile= open(fileName, 'r')
	targetFile= open(fileName+'1', 'w')
	line=srcFile.readline()
	i=0
	while line:
   	 	print line
    		i+=1
    		line=srcFile.readline()
		m=line.replace(oldStr,newStr)
		targetFile.write(m)
			
 
	print 'Total Number of Lines' ,i 
	srcFile.close()
	targetFile.close()
	os.remove(fileName)
	os.rename(fileName+'1',fileName)


You can call the above script from any other Jython script as under.

print 'We are about to replace memory setting in given domain''s setDomainEnv.cmd file'
import replaceLines

domainFolderName=sys.argv[1]
domainName=sys.argv[2]
envFileName=domainFolderName +'/'+domainName+'/bin/setDomainEnv.cmd'

replaceLines.replaceAll(envFileName, 'Xms256m', 'Xms1024m') 

In the above script, i am modifying startDomainEnv.cmd file to modify memory settings by passing domain folder location and domain name.

How to replace string in file using jython script
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *