繁体   English   中英

grep 是否有一个优雅的正则表达式来解释各种分隔符的 MAC 地址?

[英]Is there an elegant regex to grep a MAC address accounting for various delimiters?

我偶尔会在我的系统日志服务器上搜索聚合日志文件以查找特定的 MAC 地址。 由于每个源使用不同的 MAC 地址格式,我通常使用以下命令:

less syslog.log | grep -i -E '56[:-\.]?ea[:-\.]?b6[:-\.]?a6[:-\.]?82[:-\.]?5e'

无论格式或大小写如何,它都会找到地址( 56eab6a6825e56ea.b6a6.825e56:ea:b6:a6:82:5e56-EA-B6-A6-82-5E )。

我将此命令保存在文本文件中,因此我可以用相关数字替换每个十六进制对并将其粘贴,但是有没有一种优雅的方式格式化我的正则表达式,我可以将整个地址放在一起? 例如:

less syslog.log | grep -i -E '56eab6a6825e[:-\.]?(anywhereinthestring)'

我基本上想在搜索时更加懒惰,但我对环顾四周的了解不足以知道它们是否适用于这种情况。 这甚至可能吗?

这是一个 function,它接受一个 MAC 地址并从中构造一个正则表达式。 您可以像grep一样运行它,使用文件列表或从标准输入中读取任何内容。

grep-mac() {
    local mac="$1"
    local files=("${@:2}")

    # Strip punctuation from the input MAC.
    mac="${mac//[^[:alnum:]]}"
    # Create a regex by inserting `[:-\.]?` in between every two characters.
    local regex="${mac:0:2}$(sed -E 's/../[:-\\.]?\0/g' <<< "${mac:2}")"

    # Call `grep` with the regex and files we were passed.
    grep -iE "$regex" "${files[@]}"
}

MAC 地址可以是大写或小写,带或不带标点符号。 示例用法:

❯ grep-mac 56:ea:b6:a6:82:5e syslog.log | less
❯ grep-mac 56EAB6A6825E syslog.log | less

如果您想轻松访问,可以将它放在~/.bashrc中。

只需将要搜索的 mac 地址存储在变量中,然后使用 Bash 的替换扩展值生成grep的正则表达式:

mac='56:ea:b6:a6:82:5e'; grep -iE "${mac//:/[:.-]?}"

你可以试试这个grep

$ grep -Ei '56[[:alnum:]:.-]+5e' <(less syslog.log)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM