0

In bash script :

I want to replace in an html file the occurrence word 'test' with this url : url="http://www.test.com/testcom&_mc_jhc=ex_XZ-r&oh=044"

search='test'

tried sed : sed -i'.original' 's|'"${search}"'|'"${url}"'|g' index.html

it works but it replaces as well all the & with 'test'

tried with awk : awk '{sub(/test/,'"${url}"')}1'

But same issue.

why & in the url is also replaced by test?

Any solution ?

Inian
  • 80,270
  • 14
  • 142
  • 161
  • I've run into this problem a few times; try `sed "s|${search}|${url}|g" index.html > updated_index.html` – jared_mamrot Jun 29 '20 at 02:37
  • `&` is a special char in `sed` you need to escape it with backslash. – karakfa Jun 29 '20 at 02:39
  • 2
    See [this answer](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed/29613573#29613573), especially the section "Escaping a string literal for use as the replacement string in `sed`'s `s///` command". Since you're using a different delimiter (`|` instead of `/`), you'll have to adjust the pattern so it escapes that correctly. – Gordon Davisson Jun 29 '20 at 02:42
  • @GordonDavisson Thank you so much!!! you saved me lot of time, your solution works great : – sas2865423 Jun 29 '20 at 10:40
  • If you want to use sed then see [is-it-possible-to-escape-regex-metacharacters-reliably-with-sed](https://stackoverflow.com/questions/29613304/is-it-possible-to-escape-regex-metacharacters-reliably-with-sed) but personally I'd use awk but with string functions like `index()` and `substr()` instead of a regexp function like `sub()` since you seem to want to replace one literal string with another literal string rather than replace a regexp with backreference-enabled text. – Ed Morton Jun 29 '20 at 13:52

1 Answers1

-1

The Answer is to use this :

replaceEscaped=$(sed 's/[&/\]/\\&/g' <<<"$url") # escape it


sed -i'.original' 's|'"${search}"'|'"${replaceEscaped}"'|g' index.html
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
  • Since you're using `|` as a delimiter instead of `/`, you should add `|` to the list of characters to be escaped and remove `/`: `sed 's/[&|\]/\\&/g'` – Gordon Davisson Jun 29 '20 at 19:26