1

I want to search for a string enclosed in double quotes given by a positional parameter. This is what I've done:

    #!/bin/bash

    FOO=$0

    sed -i 's/"${FOO}"/bar/m' file.txt

Neither "$FOO" nor \"a${FOO}\"/ work.

I am aware that for variables to be expanded, you have to enclose the whole regex in double quotes (sed substitution with bash variables). The thing is that the string I am searching for is also enclosed in double quotes, that is why I enclosed the whole regex in single quotes. I also tried to enclose it in double quotes and escaping the double quotes, but it didn't work.

An explanation of the logic behind single and double quotes escaping would be really useful.

Community
  • 1
  • 1
Federico
  • 2,431
  • 2
  • 20
  • 34

1 Answers1

2

Use double quotes to quote the sed commands as

sed -i "s/\"${FOO}\"/bar/m" file.txt

Test:

$ echo $b
hello
$ echo \"hello\" | sed "s/\"$b\"/asdf/"
asdf
nu11p01n73R
  • 24,873
  • 2
  • 34
  • 48