Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace a string with a variable using sed

I have this string in my file

$vnet_address

And i have in my bash run time this variable which i want to replace my string with:

$vnet_address=10.1.0.0/16

I get an error when i run this command:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed -i "/\$vnet_address/ s//$vnet_address/"

And i believe it is because of the slash character ‘/’ in my variable.

How to go about it?

>Solution :

You can use

sed -i "s,\\\$vnet_address,${vnet_address}," file

Note:

  • The regex delimiter character is replaced with ,
  • The $ is properly escaped with a literal \ character

See the online demo:

#!/bin/bash
s='$vnet_address'
vnet_address=10.1.0.0/16
sed "s,\\\$vnet_address,${vnet_address}," <<< "$s"
# => 10.1.0.0/16
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading