2

如何制作一个在其标准输入中查找 IPv6 地址的 shell 命令?

一种选择是使用:

grep -Po '(?<![[:alnum:]]|[[:alnum:]]:)(?:(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}|(?:[a-f0-9]{1,4}:){1,6}:(?:[a-f0-9]{1,4}:){0,5}[a-f0-9]{1,4})(?![[:alnum:]]:?)'

此 RE 基于“匹配有效 IPv6 地址的正则表达式”中的想法,但这并不十分准确。我可以使用更丑陋的正则表达式,但有没有更好的方法,一些我不知道的命令?

4

1 回答 1

2

由于我找不到使用 shell 脚本命令的简单方法,因此我在 Python 中创建了自己的:

#!/usr/bin/env python

# print all occurences of well formed IPv6 addresses in stdin to stdout. The IPv6 addresses should not overlap or be adjacent to eachother. 

import sys
import re

# lookbehinds/aheads to prevent matching e.g. 2a00:cd8:d47b:bcdf:f180:132b:8c49:a382:bcdf:f180
regex = re.compile(r'''
            (?<![a-z0-9])(?<![a-z0-9]:)
            ([a-f0-9]{0,4}::?)([a-f0-9]{1,4}(::?[a-f0-9]{1,4}){0,6})?
            (?!:?[a-z0-9])''', 
        re.I | re.X)

for l in sys.stdin:
    for match in regex.finditer(l):
        match = match.group(0)
        colons = match.count(':')
        dcolons = match.count('::')
        if dcolons == 0 and colons == 7:
            print match
        elif dcolons == 1 and colons <= 7:
            print match
于 2012-09-13T00:36:35.693 回答