Home > Back-end >  Replace a string with a variable using sed
Replace a string with a variable using sed

Time:05-25

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:

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?

CodePudding user response:

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
  • Related