Reputation: 353
I've file that contain MAC among other information, I'm trying to replace the MAC every time it is found. the file contains something like
Dec 3 06:44:02 2013 192.168.5.21 [245]: <1234> <NOTI> |[email protected]|
request: 55:aa:cc:77:dd:bb: machine 192.168.5.21-00:11:ee:20:66:22-device-name-5
I have wrote this code, but it's not working
import re
with open("/home/user/infile.txt", "r+") as fin:
for line in fin:
mac=re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})',line, re.I).group()
for col in mac:
mac_h = mac.replace(":",'')
mac_hex = "0x" + mac_h
mac_int= int(mac_hex, 16)
new_mac = mac_int+12345
new_mac= hex(new_mac)
line= line.replace(mac, new_mac)
fin.close()
so I'm searching for mac, here I have two problems, first, it only finds the first occurrence of mac in the line. Second, when I tried the code on the second occurrence only, it got 21-00:11:ee:20:66:22
instead of just 00:11:ee:20:66:22
and then I'm doing some arithmetics (this part works), but then when I tried to replace the old value with the new one. it didn't work, I checked the file, and nothing has be replace. I can't figure out why, so can help me, please?
Update
I've changed the code, and now it write the changes to file
import re
with open("/home/user/infile.txt", "r+") as fin:
with open("/home/user/infile.txt", "w+") as f_out:
for line in fin:
mac=re.search(r'([0-9A-F]{2}[:]){5}([0-9A-F]{2})',line, re.I).group()
for col in mac:
mac_h = mac.replace(":",'')
mac_hex = "0x" + mac_h
mac_int= int(mac_hex, 16)
new_mac = mac_int+12345
new_mac= hex(new_mac)
line= line.replace(mac, new_mac)
f_out.write(line)
now the remaining problem is that it only find the first mac occurrence 55:aa:cc:77:dd:bb:
and move to the next line without matching the second one 00:11:ee:20:66:22
, so is there a way to make it continue to search after finding the first match??
Thanks
Upvotes: 1
Views: 977
Reputation: 43053
Remove the hyphen from your regex. MAC adress components are usually separated with colons.
/([\dA-F]{2}:){5}([\dA-F]{2})/i
Upvotes: 1