我偶尔会在syslog服务器上搜索聚合日志文件以获得特定的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),都会找到地址。
我将这个命令保存在文本文件中,这样我就可以用相关的数字替换每个十六进制对并粘贴到其中,但是是否有一种优雅的方式来格式化我的regex,我可以将整个地址放在一起呢?例如:
less syslog.log | grep -i -E '56eab6a6825e[:-\.]?(anywhereinthestring)'我基本上想在搜索时变得更懒,但我不太了解它们在这种情况下是否适用。这有可能吗?
发布于 2022-07-29 00:36:16
只需将要搜索的mac地址存储在变量中,并使用Bash的替换扩展值生成grep的Regex。
mac='56:ea:b6:a6:82:5e'
# Compose a regex on-the fly by replacing all colons with [:.-]?
grep -iE "${mac//:/[:.-]?}"或与某项功能相同:
grepmac() {
# Usage:
# grepmac MAC_ADDRESS FILE [FILE]...
# Parses input argument 1 as mac-address
# regardless if it uses delimiters or not.
# Returns failure if input argument 1 is not a mac-address.
[[ $1 =~ ([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2}) ]] || return 1
# Sets delimiter locally to : to join matches with colon
local -- IFS=:
# Joins matches except first to get a colon-delimited mac-address
mac="${BASH_REMATCH[*]:1}"
# Shifts out first argument away to only keep remaining file paths
shift
# Composes a regex by replacing colons in mac-address by [:.-]?
# which matches optional delimiter with : . or -
regex=${mac//:/[:.-]?}
# Performs the actual search
grep -iE "$regex" "$@"
}grepmac的跟踪执行
$ set -x; grepmac 56eab6a6825e
+ grepmac 56eab6a6825e
+ [[ 56eab6a6825e =~ ([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2})[:.-]?([[:xdigit:]]{2}) ]]
+ IFS=:
+ mac=56:ea:b6:a6:82:5e
+ shift
+ regex='56[:.-]?ea[:.-]?b6[:.-]?a6[:.-]?82[:.-]?5e'
+ grep --color=auto -iE '56[:.-]?ea[:.-]?b6[:.-]?a6[:.-]?82[:.-]?5e'发布于 2022-07-29 00:26:19
这里有一个函数,它接受MAC地址--大写或小写,有标点符号,也有标点符号--并从它构造正则表达式。您可以像运行grep一样运行它,可以使用文件列表,也可以不从stdin读取任何文件。
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[@]}"
}示例用法:
❯ grep-mac 56:ea:b6:a6:82:5e syslog.log | less
❯ grep-mac 56EAB6A6825E syslog.log | less如果您希望访问方便,可以将其放入您的~/.bashrc中。
发布于 2022-07-29 00:11:32
你可以试试这个grep
$ grep -Ei '56[[:alnum:]:.-]+5e' <(less syslog.log)https://stackoverflow.com/questions/73160255
复制相似问题