-1

The following is an extroct from a json file, that I have:

 },
   {
    "name": "asdasd",
    "script": "dsad.js",
    "merge_logs": ture,
    "error_file": "/ofghfghgfh.log",
    "out_file": "/fghgfhfgg",
    "cwd": "",
    "autorestart": true,
    "log_date_format"  : "YYYY-MM-DD HH:mm Z",
    "env": {
    "NODE_ENV": "desa",
    "KEY": "VtZOiz0Qc4afFs6j+h2r"
    }
  }]

I want to add a phrase after "KEY": substituting the value that it has now.

I tried "sed" but I added it to the end of the line

 sed '/KEY/s/$/1234/g' .json

I would need to use the "-i" option to change the file directly.

ortiga
  • 131
  • 7

3 Answers3

7

sed is the wrong tool for this job. One of the right tools is jq.

% cat wibble.json                               
[
  {
    "name": "asdasd",
    "script": "dsad.js"
  },
  {
    "log_date_format"  : "YYYY-MM-DD HH:mm Z",
    "env": {
            "NODE_ENV": "desa",
            "KEY": "VtZOiz0Qc4afFs6j+h2r"
    }
  }
]
% jq  '.[1]."env"."KEY" = "1234"' wibble.json
[
  {
    "name": "asdasd",
    "script": "dsad.js"
  },
  {
    "log_date_format": "YYYY-MM-DD HH:mm Z",
    "env": {
      "NODE_ENV": "desa",
      "KEY": "1234"
    }
  }
]
% 

It even spots that your JSON is not actually valid.

% jq . ortiga.json
parse error: Invalid literal at line 4, column 23
%
JdeBP
  • 68,745
1

You can use this (use i option to modify the file but first check if it is working properly or not):

sed -E 's/("KEY":) (".*")/\1 anything/g' .json

It will break line in two parts first will match "KEY": and then space and it will replace second part with anything.

Let us say KEY='"1234"' (by using single quote KEY's value will be "1234"). Then you can use.

sed -E "s/(\"KEY\":) (\".*\")/\1 $KEY/g" .json
Prvt_Yadav
  • 5,882
0

nested structures (like xml, html, json, etc) must be processed by utilities which are aware of the data model. if relied upon the line-aware tools like sed, awk then there always will be a chance for false positives.

hence JSON inputs must be processed by JSON aware tools. jq answer has been already given, here's an alternative solution based on jtc:

bash $ cat file.json | jtc -w'<KEY>l' -eu echo '"1234"' \;
{
   "autorestart": true,
   "cwd": "",
   "env": {
      "KEY": "1234",
      "NODE_ENV": "desa"
   },
   "error_file": "/ofghfghgfh.log",
   "log_date_format": "YYYY-MM-DD HH:mm Z",
   "merge_logs": true,
   "name": "asdasd",
   "out_file": "/fghgfhfgg",
   "script": "dsad.js"
}
bash $ 
Dmitry
  • 1