1

I've to substitute the string blacklist:[/^\/_/,/\/[^\/?]+\.[^\/]+$/] with blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/, /\/first|\/second|\/third/] in a file. I would like to use sedcommand to do it in shell. I opted to use ~ as separator and I tried with variables but nothing happened.

Example:

VarA="blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/]"

VarB="blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/, /\/first|\/second|\/third/]"

sed "s~$VarA~$VarB~" service-worker.js

Could you help me please? Thanks

  • 1
    See if https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed helps. If that looks complicated, see https://unix.stackexchange.com/questions/129059/how-to-ensure-that-string-interpolated-into-sed-substitution-escapes-all-metac – Sundeep Jul 15 '20 at 10:28

2 Answers2

1

sed doesn't understand literal strings, just use a tool that does like awk:

$ cat file
foo
blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/]
bar

$ VarA='blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/]'

$ VarB='blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/, /\/first|\/second|\/third/]'

$ VarA="$VarA" VarB="$VarB" awk '
    BEGIN { old=ENVIRON["VarA"]; lgth=length(old); new=ENVIRON["VarB"] }
    s = index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+lgth) }
    { print }
' file 
foo
blacklist: [/^\/_/,/\/[^\/?]+\.[^\/]+$/, /\/first|\/second|\/third/]
bar
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

some meta-characters like \ [ $ must be quoted in single quotes (which is not possible in your case) or escaped (with backslash, which must escaped with itself too)

you can use string manipulation for replacing

run this function over your strings

escape() {
  local var="$1"

  var="${var//\\/\\\\}" # \
  var="${var//\[/\\\[}" # [
  var="${var//\$/\\\$}" # $
  printf "%s" "$var"

  return 0
}

VarA=$(escape "$VarA")
VarB=$(escape "$VarB")
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
alecxs
  • 701
  • 8
  • 17
  • there is maybe easier way just `printf -v VarA '%q' "$VarA"` but my version of printf does error *"bad format"* https://stackoverflow.com/q/15783701 – alecxs Jul 15 '20 at 23:42
  • `. ^ *` should be escaped too. also please choose other name for function (may exist) https://stackoverflow.com/q/399078 – alecxs Jul 15 '20 at 23:55