Let's say that I have a file that contains different MAC address notations of multiple MAC addresses. I want to replace all the matching notations of one MAC address I have parsed from an argument input. So far my script generates all the notations I need and can loop through the lines of the text and show the lines that have to be changed.
import argparse, sys
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--filename")
parser.add_argument("-m", "--mac_address")
args = parser.parse_args()
mac = args.mac_address #In this case 00:1a:e8:31:71:7f
colon2 = mac #00:1a:e8:31:71:7f
dot2 = colon2.replace(":",".") # 00.1a.e8.31.71.7f
hyphen2 = colon2.replace(":","-") # 00-1a-e8-31-71-7f
nosymbol = colon2.replace(":","") # 001ae831717f
colon4 = ':'.join(nosymbol[i:i+4] for i in range(0, len(nosymbol), 4)) # 001a:e831:717f
dot4 = colon4.replace(":",".") # 001a.e831.717f
hyphen4 = colon4.replace(":","-") # 001a-e831-717f
replacethis = [colon2,dot2,hyphen2,dot4,colon4,nosymbol,hyphen4]
with open(args.filename, 'r+') as f:
text = f.read()
for line in text.split('\n'):
for n in replacethis:
if line.replace(n, mac) != line:
print line + '\n has to change to: \n'line.replace(n,mac)
else:
continue
If the file would look like this:
fb:76:03:f0:67:01
fb.76.03.f0.67.01
fb-76-03-f0-67-01
001a:e831:727f
001ae831727f
fb76.03f0.6701
001ae831727f
fb76:03f0:6701
001a.e831.727f
fb76-03f0-6701
fb7603f06701
it should change to:
fb:76:03:f0:67:01
fb.76.03.f0.67.01
fb-76-03-f0-67-01
00:1a:e8:31:71:7f
00:1a:e8:31:71:7f
fb76.03f0.6701
00:1a:e8:31:71:7f
fb76:03f0:6701
00:1a:e8:31:71:7f
fb76-03f0-6701
fb7603f06701
I am struggling at writing the new lines containing the changed MAC address notation back to the file replacing the previous line.
Is there a way to do this?