Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a Json object from Json File by sed command in BASH

Tags:

json

bash

sed

awk

I a have a JSON file in which a JSON object needs to be deleted. Is there any way to delete it by using the sed command only? My sample file is given below.

{
  "name": "ABC",
  "description": "XYZ",
  "versions": {},
  "json_class": "Chef::Environment",
  "chef_type": "environment",
  "default_attributes": {},
  "override_attributes": {
    "company": {
      "xyz": {
        "mailer": {
          "smtp_host": "Some IP",
          "imap_host": "Some Host",
          "imap_user": "Some UserId",
          "reply_to": "Some User Id",
          "outbound_user": "",
          "imap_mail_domain": "compute.oraclecloud.com",
          "imap_password": ""
        },
        "logicaldomainname": ""
      }
    }
  }
}

I want to delete the mailer object from the file using the sed command. Please take a look and let me know if it is possible using the sed command.

My main motive of this deletion is to replace this object with new mailer object so that the next time when another mailer object will be posted then we will append it in xyz JSON object.

Expected output:

{
  "name": "ABC",
  "description": "",
  "version": {},
  "json_class": "Chef::Environment",
  "chef_type": "environment",
  "default_attributes": {},
  "override_attributes": {
    "Company": {
      "XYZ": {
        "logicaldomainname": ""
      }
    }
  }
}
like image 600
Jitendra Yadav Avatar asked Sep 20 '25 12:09

Jitendra Yadav


1 Answers

Using sed:

sed '/\"mailer\"/,/}/ d; /^$/d' 1.a

"Delete from mailer to the first }, then delete all blank lines (you input has one)".

To overwrite the file ("in-place")

sed -i ...

Note: works for multiline files (as yours).

like image 50
John_West Avatar answered Sep 23 '25 10:09

John_West