1

I have a .env file containing the following:

{
    "Config" : {
        "host" : "XX.XXX.XX.XXX" ,
        "port" : 3019
    }
}

In a bash script I have an a variable $myNewIP. I want to replace the IP in the file with the value of my variable with an awk command.

I have tried

awk '/host/{sub(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})}1 .env

I am prompted that I have syntax errors. I thought this should work. What is wrong with the command?

Gene
  • 104
  • 15
  • 1
    awk doesn't support `\d`, use `[0-9]` instead.. use `\.` instead of `\\.` ... also, you haven't specified replacement string for `sub` and closing `'` is missing after `1` ... see https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script wrt passing shell variables to awk – Sundeep Apr 16 '20 at 04:53

1 Answers1

2

You should use a JSON-aware tool like jq to manipulate JSON files, not awk, sed, etc:

jq --arg myNewIP "$myNewIP" '.Config.host = $myNewIP' .env
{
  "Config": {
    "host": "127.0.0.1",
    "port": 3019
  }
}
Shawn
  • 47,241
  • 3
  • 26
  • 60