-1

I have a set of ip addresses declared to a variable IP

IP=["https://127.0.0.1", "https://127.0.0.2", "https://127.0.0.3"]

Need to subtitute the value of IP in some file so i use the sed command

sed -i 's/#hosts: \["https:\/\/localhost:80"\]/hosts: ['$IP']/g' someFile

This errors out with

sed: -e expression #1, char 84: unknown option to `s'

So i tried, which works fine, notice the \ escapes on the IP addresses

sed -i 's/#hosts: \["https:\/\/localhost:80"\]/hosts:["https:\/\/127.0.0.1", "https:\/\/127.0.0.2", "https:\/\/127.0.0.3"]/g'

expected results:

hosts: ["https://127.0.0.1", "https://127.0.0.2", "https://127.0.0.3"]

I can't really influence the value of IP variable because it's gotten from a parameter store with other applications using it. I'm assuming I need to write a function to do the escapes after getting the value from the parameter store? Thanks

badman
  • 319
  • 1
  • 12

1 Answers1

0

The primary issue is you're using sed's default script delimiter of /, which also shows up in the data/strings you're processing, with the net result being that sed can't tell which / are script delimiters vs data.

One solution, as you've figured out, is to escape the / that show up as data.

Another solution is to use a different character (that doesn's show up in the data) as the sed script delimiter.

Addressing a couple other issues with the current code, and using | as the sed script delimiter:

IP='["https://127.0.0.1", "https://127.0.0.2", "https://127.0.0.3"]'  # wrap value in single quotes so the whole line is treated as part of the assignment to IP

sed -i "s|#hosts: \[https://localhost:80\]|hosts: $IP|g" someFile   # wrap script in double quotes to allow for expansion of $IP

This generates:

$ cat someFile
hosts: ["https://127.0.0.1", "https://127.0.0.2", "https://127.0.0.3"]
markp-fuso
  • 28,790
  • 4
  • 16
  • 36