简体   繁体   English

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

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

I will occasionally search aggregate logs files on my syslog server for a specific MAC address.我偶尔会在我的系统日志服务器上搜索聚合日志文件以查找特定的 MAC 地址。 Since each source uses a different format for MAC addresses, I usually use this command:由于每个源使用不同的 MAC 地址格式,我通常使用以下命令:

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

Which will find the address regardless of the format or case ( 56eab6a6825e , 56ea.b6a6.825e , 56:ea:b6:a6:82:5e , 56-EA-B6-A6-82-5E ).无论格式或大小写如何,它都会找到地址( 56eab6a6825e56ea.b6a6.825e56:ea:b6:a6:82:5e56-EA-B6-A6-82-5E )。

I have this command saved in text file so I can just replace each hex pair with the relevant digits and paste it in, but is there an elegant way format my regex where I can have the whole address together?我将此命令保存在文本文件中,因此我可以用相关数字替换每个十六进制对并将其粘贴,但是有没有一种优雅的方式格式化我的正则表达式,我可以将整个地址放在一起? For example:例如:

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

I basically want to be more lazy when searching, but I don't understand lookarounds enough to know if they are applicable in this case.我基本上想在搜索时更加懒惰,但我对环顾四周的了解不足以知道它们是否适用于这种情况。 Is this even possible?这甚至可能吗?

Here's a function that takes a MAC address and constructs a regex from it.这是一个 function,它接受一个 MAC 地址并从中构造一个正则表达式。 You can run it just like grep , with either a list of files or nothing to read from stdin.您可以像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[@]}"
}

The MAC address can be uppercase or lowercase, with or without punctuation. MAC 地址可以是大写或小写,带或不带标点符号。 Example usage:示例用法:

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

You can put it in your ~/.bashrc if you want easy access.如果您想轻松访问,可以将它放在~/.bashrc中。

Simply store the mac-address to search in a variable and use Bash's replace expanded value to generate the Regex for grep :只需将要搜索的 mac 地址存储在变量中,然后使用 Bash 的替换扩展值生成grep的正则表达式:

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

You can try this grep你可以试试这个grep

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

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

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