-1

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?

  • 3
    In attach dupe 1st 2 answers https://stackoverflow.com/a/19152051/5866580 and https://stackoverflow.com/a/19152302/5866580 will work in your case, we need to just put string and variable names in place of the shown examples, Logic is same where it shows how to escape a dollar string and how to use a shell variable in `sed`. – RavinderSingh13 May 25 '22 at 04:09

1 Answers1

1

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
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563