Ashish
Ashish

Reputation: 57

How to find and replace MAC address

I have a file which has a data-

a AA:22:CC:44:DD:66 bbc aa:44:55:77:dd:rr axa
AA:22:CC:44:DD:66 sds 77:dd:rr:aa:44:55 dd 00:3a:7d:52:16:01 dd

My requirement is to find all the MAC addresses and replace it with XX:XX:XX:XX:XX:XX

So my final output should be-

a XX:XX:XX:XX:XX:XX bbc XX:XX:XX:XX:XX:XX axa
XX:XX:XX:XX:XX:XX sds XX:XX:XX:XX:XX:XX dd XX:XX:XX:XX:XX:XX dd

I have tried below, but it doesn't work fully

sed -r 's/(.*)([a-zA-Z0-9]{2}:[a-zA-Z0-9]{2}:[a-zA-Z0-9]{2}:[a-zA-Z0-9]{2}:[a-zA-Z0-9]{2}:[a-zA-Z0-9]{2})(.*)/\1\XX:XX:XX:XX:XX:XX\3/g' file.txt

Upvotes: 3

Views: 469

Answers (2)

kvantour
kvantour

Reputation: 26491

Since the pattern of a MAC is rather unique, you could make it short as:

sed -e 's/..:..:..:..:..:../XX:XX:XX:XX:XX:XX/g'

This however might accidentally change other strings that could match this pattern. If you have to be 100% certain, then use the solution of RavinderSingh13

Upvotes: 3

RavinderSingh13
RavinderSingh13

Reputation: 133600

With your shown samples, try following. Written and tested with shown samples in GNU sed.

sed -E 's/([0-9a-eA-E]{2}:){5}[0-9a-eA-E]{2}/XX:XX:XX:XX:XX:XX/g' Input_file

Explanation: Simply using -E option of sed which enables ERE for regex. Then using s(substitution option) to substitute ([0-9a-eA-E]{2}:){5} digits, alphabets(small OR capital letters) 2 in number followed by a colon, then this combination should be there 5 times{5} and then again matching alphabets(small, capital letters) and digits 2 occurrences if match is found of this regex substitute them with XX:XX:XX:XX:XX:XX. using g option to globally substitute all matched/found matched ones with new value.

Upvotes: 3

Related Questions