I would like to replace text in a file using a regexp and Python. Using sed I can can do something like this on the command line
sed -r 's/([0-9]{1,3}\.)([0-9]{1,3}\.)([0-9]{1,3}\.)([0-9]{1,3})/\1\2xx.xx/' ./input/my_file > ./output/my_file_new
Which basically takes looks for a string of ip=[4 octets] and replaces the last two with xx.
The input file would look like
name=rockband&ip=176.4.23.71&releasedate=none
name=rockband2&ip=121.1.44.52&releasedate=none
The desired output file looks like
name=rockband&ip=176.4.xx.xx&releasedate=none
name=rockband2&ip=121.1.xx.xx&releasedate=none
I need to put this into a Python script I am using
import re
regexp = re.compile(r's/([0-9]{1,3}\.)([0-9]{1,3}\.)([0-9]{1,3}\.)([0-9]{1,3})/\1\2xx.xx/')
def replace(source_file_path):
fh, target_file_path = mkstemp()
with codecs.open(target_file_path, 'w', 'utf-8') as target_file:
with codecs.open(source_file_path, 'r', 'utf-8') as source_file:
for line in source_file:
print(line)
target_file.write( !! How to use sub in here )
remove(source_file_path)
move(target_file_path, source_file_path)
How can I use the sub() method to achieve what I want to do? I need to pass 3 arguments to this method and can only think of how to pass 2, I don't know what that third argument should be
target_file.write(re.sub(regexp, line))
.into axbefore the first&?sedsyntax, your sub expect what to match and what to replace it as two arguments.