Search Replace a string in Python

#!/usr/bin/env python

# Ashish Disawal, 18 Nov 2010
# This program reads a file, search for lines starting with "MY_NUM[0]",  where 0

# varies. It then replaces 0 with a serialized number.


import re, sys, os

file = sys.argv[1]
tmp_file = ".tmp_" + file
last_file = ".last_" + file

fd = open(file, 'r')
tmp_fd = open(tmp_file, 'w')
count = 0

for line in fd.readlines():
  if re.match("DST_IP", line):
    replace_str = "DST_IP[" + str(count) + "]"
    count = count + 1
    tmp_fd.write(re.sub("DST_IP\[\d+\]", replace_str, line))
  else:
    tmp_fd.write(line)

print 'Backing up current file "' + file + '" as "' + last_file + '"'
os.rename(file, last_file)

print 'Moving tmp file "' + tmp_file + '" as "' + file + '"'
os.rename(tmp_file, file)

Comments

Popular Posts