Reputation: 1618
I've got a valid mac address in a var called oldMAC
I need to increment this and then return a new valid MAC Address.
In this example I'm incrementing by 1, but it could be by any value.
So far I've got the following:
echo $oldMAC
mac=$(echo $oldMAC | tr '[:lower:]' '[:upper:]' | tr -d ':') # upper case and remove :
echo $mac
macdec=$( printf '%d\n' 0x$mac ) # convert to decimal
echo $macdec
macadd=$( expr $macdec + 1 ) # add 1
echo $macadd
machex=$( printf '%X\n' $macadd ) # convert to hex
echo $machex
This outputs:
00:12:34:ae:BC:EF (oldMAC)
001234AEBCEF (mac)
78193278191 (macdec)
78193278192 (madadd)
1234AEBCF0 (machex)
The issue I have is working out how to convert 1234AEBCF0
so it returns as 00:12:34:AE:BC:F0
Can anyone advise how to do this... or is there a better way ?
Thanks
Upvotes: 2
Views: 2779
Reputation: 129
Just need to change 2 lines.
mac=$(echo $oldMAC | tr '[:lower:]' '[:upper:]' | tr -d ':')
to
mac=$(echo $oldMAC | sed s/":"//g)
and then
machex=$( printf '%X\n' $macadd )
to
machex=$( printf '%X\n' $macadd |tee|tr A-Z a-z)
overall
mac=$(echo $oldMAC|sed s/":"//g)
macdec=$(printf '%d\n' 0x$oldmac)
macadd=$(expr $macdec + 1)
machex=$( printf '%X\n' $macadd |tee|tr A-Z a-z)
Upvotes: 1
Reputation: 76306
sed
to rescue:
macnew=$(echo $machex | sed 's/../&:/g;s/:$//')
The pattern is
+------------ substitute
| +--------- any two characters
| | +------- with the whole match
| | |+------ and :
| | || +---- all occurrences, utilizing the fact it means non-overlapping
| | || |+------- another command
| | || ||+------ substitute
| | || || +---- :
| | || || |+--- at the end of line
| | || || || +- with nothing to get rid of the trailing :
V V VV VV VV V
s/../&:/g;s/:$//
You also need to make sure 12 digits are actually printed. The printf
command can do that, just make the pattern "%012x"
—0
means pad with 0
s (instead of spaces) and 12
is the minimum width. Use uppercase X
for uppercase hex digits and lowercase x
for lowercase hex digits.
You can simplify the addition a bit by using the bash's built-in arithmetic expansion, which understand hexadecimal output directly, and understands both upper and lowercase, so you only need to drop the :
s:
mac=$(echo $oldMAC | tr -d ':')
macadd=$(( 0x$mac + 1 ))
It still comes back as decimal, so you still need the printf "%012x" to convert it. You can pipe it directly to the sed to keep it short.
macnew=$(printf "%012x" $macadd | sed 's/../&:/g;s/:$//')
Upvotes: 2