[英]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'
無論格式或大小寫如何,它都會找到地址( 56eab6a6825e
、 56ea.b6a6.825e
、 56:ea:b6:a6:82:5e
、 56-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.