Monday, October 24, 2022

[SOLVED] Awk or sed to prepend missing zeros in mac addresses

Issue

I've got a file consisting of IPs and MAC address pairs and I need to pad the MAC addresses with zeros in each octet, but I don't want to change the IP. So this...

10.5.96.41 0:0:e:4c:b7:42
10.5.96.42 c4:f7:0:13:ef:32
10.5.96.43 0:e8:4c:60:2b:42
10.5.96.44 0:6a:bf:b:35:f1

Should get changed to this...

10.5.96.41 00:00:0e:4c:b7:42
10.5.96.42 c4:f7:00:13:ef:32
10.5.96.43 00:e8:4c:60:2b:42
10.5.96.44 00:6a:bf:0b:35:f1

I tried sed 's/\b\(\w\)\b/0\1/g' but that produces:

10.05.96.41 00:00:0e:4c:b7:42
10.05.96.42 c4:f7:00:13:ef:32
10.05.96.43 00:e8:4c:60:2b:42
10.05.96.44 00:6a:bf:0b:35:f1

which is not desired because I only want to effect the MAC address portion.


Solution

Since you've tagged macos, I'm not sure if this will work for you. I tested it on GNU awk

$ awk '{gsub(/\<[0-9a-f]\>/, "0&", $2)} 1' ip.txt
10.5.96.41 00:00:0e:4c:b7:42
10.5.96.42 c4:f7:00:13:ef:32
10.5.96.43 00:e8:4c:60:2b:42
10.5.96.44 00:6a:bf:0b:35:f1

awk is good for field processing, here you can simply perform substitution only for second field

But, I see \b and \w with your sed command, so you are using GNU sed? If so,

sed -E ':a s/( .*)(\b\w\b)/\10\2/; ta' ip.txt


With perl

$ perl -lane '$F[1] =~ s/\b\w\b/0$&/g; print join " ", @F' ip.txt
10.5.96.41 00:00:0e:4c:b7:42
10.5.96.42 c4:f7:00:13:ef:32
10.5.96.43 00:e8:4c:60:2b:42
10.5.96.44 00:6a:bf:0b:35:f1

If you want to get adventurous, specify that you want to avoid replacing first field:

perl -pe 's/^\H+(*SKIP)(*F)|\b\w\b/0$&/g' ip.txt


Answered By - Sundeep
Answer Checked By - Mildred Charles (WPSolving Admin)