0

I am trying add an object to a json file using bash. for example below is the final result I am aiming for

{
   ....,
   "publishConfig": {
    "registry": "http://myapp.org:4873/"
   }
}

So I am using the following bash command in a script

sed -i '$s/}/,\n"publishConfig":{\n\t"registry":"http://myapp.org:4873/"\n}\n}/' somefile.json

however I keep getting the following error

char 48: unknown option to 'm

can someone please help me out with this regex. Thanks in advance.

Shadid
  • 4,133
  • 9
  • 30
  • 53

2 Answers2

5

The slashes in the regular expression are unescaped. You should escape them with backslash:

sed -i '$s/}/,\n"publishConfig":{\n\t"registry":"http:\/\/myapp.org:4873\/"\n}\n}/' somefile.json

But I'd recommend to choose a tool with a built-in JSON support, such as PHP. Or a programming language capable of handling JSON.

Update

For example, in NodeJS:

node <<'EOS'
var fs = require("fs");

var filename = 'somefile.json';

var s = fs.readFileSync(filename, {encoding: 'utf-8'});
var o = JSON.parse(s);
o.publishConfig =  { registry: "http://myapp.org:4873/" };

fs.writeFileSync(filename, JSON.stringify(o, null, '\t'));
EOS

(used Bash here document)

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
0

The following should work:

sed -i '$s/}/,\n"\tpublishConfig": {\n\t"registry":"http://myapp.org:4873/"\n\t}\n\n}/' somefile.json.

But better use something like python or jq for this sort of actions.

Moreover, the action you are seeking is similar to merging two json files. Sed can merge two but how will you merge 1000 JSON files. If you start doing that by sed or awk, it will be terrible for you. But if you use something like Python, you can do it through program. Hope it helps.

deosha
  • 972
  • 5
  • 20