Reputation: 49
I have this existing pattern:
ethernet0.generatedAddress = "00:50:56:bf:71:06"
I need to replace a mac address in the above expression with a new mac address using a sed pattern. Note: The mac-address that needs to replaced is not same everytime.
I tried this sed expression , but no luck..
sed 's/ethernet0.generatedAddress.*=.*\"([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}/ethernet0.generatedAddress = \"00:16:3e:5e:1d:01'
Thanks in Advance
Upvotes: 1
Views: 822
Reputation: 41460
Why not use awk
? It gives simple and easy to understand solution.
cat file
some data
ethernet0.generatedAddress = "00:50:56:bf:71:06"
more data
mac="ab:11:23:55:11:cc"
awk -v m="$mac" -F' "|"' '/ethernet0.generatedAddress/ {$2="\""m"\""}1' file
some data
ethernet0.generatedAddress = "ab:11:23:55:11:cc"
more data
It search for ethernet0.generatedAddress
, if found, replace field #2
separated by "
with new mac.
If one extra space is not problem, this would be more clean:
awk -v m="$mac" -F\" '/ethernet0.generatedAddress/ {$2=FS m FS}1' file
some data
ethernet0.generatedAddress = "ab:11:23:55:11:cc"
more data
Or this:
awk -v m="\"$mac\"" -F\" '/ethernet0.generatedAddress/ {$2=m}1' file
Upvotes: 1
Reputation: 9235
Pattern:
([a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2}:[a-z0-9]{2})
Or the following one if uppercase letters are used
([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})
Replacement:
new_mac_address // for instance 00:f6:a0:ff:f1:06
Side note: As has been pointer in the comments below, escape parentheses and curly brackets if needed or use -r
option
Using sed
it would be something like this (just tested)
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\NEW_MAC_ADDRESS\3/g' file.txt
Use -i
option in addition if you want to replace the file on-the-fly
Content of the tested file (file.txt)
something before ethernet0.generatedAddress = "00:50:56:bf:71:06" and something after
Upvotes: 2