0

To modify a specific line of a Javascript library, I wrote a shell script using Sed's regex, but I am getting errors because the line of library includes Javascript's Regex, seems Sed thinks it is a part of him. If the line is a normal text, it works well as I expected.

#!/bin/bash

replace() {
    if [[ "$OSTYPE" == "darwin"* ]]; then
      sed -i "" "s/$1/$2/g" "$3"
    else
      sed -i "s/$1/$2/g" "$3"
    fi
}

# ==========================
# Fix HTML Entities
# ==========================
# 
# [']: '
# [>]: >

replace "return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/\"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;');" \
        "return str.replace(ampregex, '&amp;').replace(/</g, '&lt;').replace(/\"/g, '&quot;').replace(/\t/g, '&#x9;').replace(/\n/g, '&#xA;').replace(/\r/g, '&#xD;').replace(/'/g, '&apos;').replace(/>/g, '&gt;');" \
        "node_modules/xmlbuilder/lib/XMLStringifier.js"
coturiv
  • 2,880
  • 22
  • 39
  • 2
    This is an issue with any regex tool - if you give it a string that contains regex syntax, it's going to treat it as regex syntax. You either need to escape that string or, if possible, instruct the tool to only treatthe string as plain text. – VLAZ Jan 08 '21 at 07:45
  • 2
    This might be a better duplicate: [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/). – Gordon Davisson Jan 08 '21 at 08:05
  • Thanks @GordonDavisson, that's exactly what I was looking for. – coturiv Jan 08 '21 at 08:22

0 Answers0