【问题标题】:Finding and replacing string (mac address) in a file is not working在文件中查找和替换字符串(mac 地址)不起作用
【发布时间】:2014-01-31 02:34:48
【问题描述】:

我的文件包含 MAC 以及其他信息,每次找到 MAC 时我都会尝试替换它。 该文件包含类似

Dec  3 06:44:02 2013 192.168.5.21 [245]: <1234> <NOTI> |machine1@192.168.5.21|
request: 55:aa:cc:77:dd:bb: machine 192.168.5.21-00:11:ee:20:66:22-device-name-5

我已经写了这段代码,但它不起作用

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()

所以我正在搜索mac,这里我有两个问题,首先,它只找到该行中第一次出现的mac。其次,当我仅在第二次出现时尝试代码时,它得到21-00:11:ee:20:66:22 而不仅仅是00:11:ee:20:66:22

然后我正在做一些算术(这部分有效),但是当我尝试用新值替换旧值时。它没有用,我检查了文件,没有任何东西可以替换。 我不知道为什么,请帮帮我?

更新

我已经更改了代码,现在它将更改写入文件

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)

现在剩下的问题是它只找到第一个mac出现55:aa:cc:77:dd:bb:并移​​动到下一行而不匹配第二个00:11:ee:20:66:22,所以有没有办法让它在找到第一个匹配后继续搜索?? 谢谢

【问题讨论】:

  • 如果您使用的是with,那么我认为没有理由明确关闭该文件。
  • 你没有在任何地方更新文件,你只是在设置变量line
  • 但我使用的是replace() ??
  • 这不会将数据写回文件!如果您不想匹配破折号,只需使用: 而不是[:-]
  • re.compile编译模式。使用os.rename 重命名文件。打开它阅读。使用原始名称打开一个新文件进行写入。循环遍历文件的行。将模式的sub method 与转换匹配对象的MAC 地址的函数一起使用。使用os.remove删除原文件。

标签: python regex string python-3.x


【解决方案1】:

从您的正则表达式中删除连字符。 MAC 地址组件通常用冒号分隔。

/([\dA-F]{2}:){5}([\dA-F]{2})/i

【讨论】:

    猜你喜欢
    • 2011-05-25
    • 2013-02-19
    • 2020-08-12
    • 1970-01-01
    • 2012-08-25
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多