Reputation: 171
I'm writing a script on bash to read MAC address from a group of devices and I'm stucked with one switch that returns address without leading 0. For instance:
0:A:B:11:22:C -> that would be -> 00:0A:0B:11:22:0C
Is there any way a regex could add these leading zeroes? I could take each address separately, take its bytes and adjust it, but I was wondering if there's an easier way.
Upvotes: 0
Views: 1738
Reputation: 785481
Here is way to do this in BASH itself using read
and printf
built-ins:
s='0:A:B:11:22:C'
IFS=: read -ra arr <<< "$s"
printf -v str "%02s:" "${arr[@]}"
echo "${str%:}"
00:0A:0B:11:22:0C
Upvotes: 0
Reputation: 174766
You could use sed. \b
matches between a word character and a non-word character. So \b\(\w\)\b
captures the substring which has a single word character.
sed 's/\b\(\w\)\b/0\1/g' file
Example:
$ echo '0:A:B:11:22:C' | sed 's/\b\(\w\)\b/0\1/g'
00:0A:0B:11:22:0C
Upvotes: 4