如何获得包含带有sed或awk的MAC地址的字段号? [英] How can I get the field number that contains a MAC address with sed or awk?
问题描述
我正在尝试获取包含某种模式(在本例中为MAC地址)的字段号.想象一下,我们有这样的事情:
I'm trying to get the field number that contains a certain pattern (in this case a MAC address). Imagine we have something like this:
AAA BBB CCC xx:xx:xx:xx:xx:xx EEE FFF GGG
其中xx:xx ...是MAC地址,因此x是字母数字.
Where xx:xx... is a MAC address, so x's are alphanumeric.
如果使用该行作为输入,我想获取MAC地址所在的字段的编号.在这种情况下,为"4".
If I use that line as the input, I want to obtain the number of the field where the MAC address is. In this case, "4".
我在想sed或awk,但不知道如何输出字段号.
I was thinking of sed or awk, but don´t know how to output the field number.
推荐答案
使用NF遍历字段
使用for循环,使用POSIX字符类的十六进制数字对照正则表达式检查每个字段.找到匹配项后,打印匹配的字段号.
Loop Over Fields With NF
Use a for-loop to check each field against a regular expression, using the POSIX character class for hexadecimal digits. When a match is found, print the matching field number.
echo 'AAA BBB CCC 00:00:00:00:00:00 EEE FFF GGG' |
awk '{ for (i=1; i<=NF; i++)
if ($i ~ /^([[:xdigit:]]{2}:){5}[[:xdigit:]]$/)
print i
next
}'
4
这篇关于如何获得包含带有sed或awk的MAC地址的字段号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!