在文本文件(Mac地址)中查找并替换正则表达式

有人问过其他地方,但是尝试这些解决方案时并不高兴。我正在尝试使用open(file)而不是文件输入来搜索和替换。原因是我正在打印“ y of y complete”消息(fileinput将其放入文件中而不是发送至终端)。我的测试文件是用换行符分隔的100个mac地址。

我要做的就是找到与mac地址匹配的正则表达式,然后将其替换为“ MAC ADDRESS WAS HERE”。下面是我所拥有的,它只将替换字符串放在文件底部一次。

#!/usr/bin/env python3
import sys
import getopt
import re
import socket
import os
import fileinput
import time

file = sys.argv[1]

regmac = re.compile("^(([a-fA-F0-9]{2}-){5}[a-fA-F0-9]{2}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})?$")
regmac1 = "^(([a-fA-F0-9]{2}-){5}[a-fA-F0-9]{2}|([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})?$"
regv4 = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$')
regv41 = '^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$'

menu = {}
menu['1']="MAC"
menu['2']="IPV4"
menu['3']="IPV6"
menu['4']="STRING"
menu['5']="EXIT"

while True:
    options=menu.keys()
    sorted(options)
    for entry in options:
        print(entry, menu[entry])

    selection = input("Please Select:")
    if selection == '1':
        print("MAC chosen...")
        id = str('mac')
        break
    elif selection == '2':
        print("IPV4 chosen")
        id = str('ipv4')
        break
    elif selection == '3':
        print("IPV6 chosen")
        id = str('ipv6')
        break
    elif selection == '4':
        print("String chosen")
        id = str('string')
        break
    elif selection == '5':
        print("Exiting...")
        exit()
    else:
        print("Invalid selection!")

macmatch = 0
total = 0

while id == 'mac': 
    with open(file, 'r') as i:
        for line in i.read().split('\n'):
            matches = regmac.findall(line)
            macmatch += 1
        print("I found",macmatch,"MAC addresses")
        print("Filtering found MAC addresses")
    i.close()

    with open(file, 'r+') as i:
        text = i.readlines()
        text = re.sub(regmac, "MAC ADDRESS WAS HERE", line)
        i.write(text)

上面将在最后一行的末尾放置“ MAC ADDRESS WAS HERE”,而不替换任何MAC地址。 我从根本上错过了一些东西。如果有人能指出我正确的方向,那就太好了!

请注意,我通过fileinput进行了此工作,但无法显示其进度,因此请尝试在上面使用。再次感谢!