Reputation: 1523
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
Where xx:xx... is a MAC address, so x's are alphanumeric.
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".
I was thinking of sed or awk, but don´t know how to output the field number.
Upvotes: 1
Views: 236
Reputation: 6333
sed would work:
echo YOUR_STRING | sed -n 's/.*\([a-zA-Z0-9]\{2\}\(:[a-zA-Z0-9]\{2\}\)\{5\}\).*/\1/p'
Example:
echo abc ab:ab:ab:ab:ab:ab abc | sed -n 's/.*\([a-zA-Z0-9]\{2\}\(:[a-zA-Z0-9]\{2\}\)\{5\}\).*/\1/p'
ab:ab:ab:ab:ab:ab
Upvotes: 1
Reputation: 84393
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
Upvotes: 2