Search code examples
jsonregexsedreplacesh

Invalid preceding regular expression with SED


I'm trying to replace a JSON value using SED regular expression. However, I'm experiencing the following error:

sed: -e expression #1, char 60: Invalid preceding regular expression

I have the following JSON object:

{
  "profiles":{
    "http":{
      "applicationUrl":"http://localhost:5123"
    }
  }
}

I used regex101.com to create the following regular expression (PCRE2 - PHP >= 7.3):

(?<="applicationUrl": ")[^"]+(?=")

Here is a link with the regular expression and JSON object. https://regex101.com/r/OwWRbc/1

I used regex101 code generator function to generate a SED command.

sed -E 's/(?<="applicationUrl": ")[^"]+(?=")/http:\/\/0.0.0.0:80/gm;t;d'

Here is a link to a SED validator showing the error: https://sed.js.org/index.html?snippet=y7en7e

I'm expecting the JSON object to be updated as follows:

{
  "profiles": {
    "http": {
      "applicationUrl": "http://0.0.0.0:80"
    }
  }
}

I have also tried to replace the forward slash with hash

sed -E 's#(?<="applicationUrl": ")[^"]+(?=")#http:\/\/0.0.0.0:80#gm;t;d'

Solution

  • This command:

    sed -E 's/"applicationUrl": "[^"]+"/"applicationUrl": "http:\/\/0.0.0.0:80"/' input.json > output.json
    

    reads the input JSON from input.json and writes the updated JSON to output.json. It replaces the value of "applicationUrl" with http://0.0.0.0:80.