2

Json file as follows:

{

      "ImageId": "ami-074acc26872f26463",
      "KeyName": "Accesskeypair",
      "SecurityGroupIds": ["sg-064caf9c470e4e8e6"],
      "InstanceType": ""
      "Placement": {
        "AvailabilityZone": "us-east-1a"
      }
}

read type #input from user

now i want to add json value in "InstanceType": "$type" in file using bash script i have tried sed, cat and echo

echo "Hello"
echo "lets create an instance"  
echo "please enter the type of instance you need"
read instance_type;
echo $type
 sed -a '|\InstanceType": "|$instance_type|a' awsspotinstancecreation.json
 sed -e '/\"InstanceType": "|$instance_type|/a' awsspotinstancecreation.json
 sed -i "/\InstanceType": "/ s/^\(.*\)\('\)/\1, $instance_type/" awsspotinstancecreation.json
 sed -e 's/^"InstanceType": "",.*$/"InstanceType": "$instance_type",/g' awsspotinstancecreation.json
 sed -i 's/^InstanceType .*$/"InstanceType": "$instance_type",/' awsspotinstancecreation.json
 sed -i 's:^"InstanceType": "",.*$:"InstanceType": "$instance_type",:a' awsspotinstancecreation.json

but when I do it comes "InstanceType": "$type" instead of "InstanceType": "t2.small"

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
shrikkanth roxor
  • 237
  • 1
  • 3
  • 8
  • 1
    Please go back and edit your [original question](https://stackoverflow.com/questions/56520896/how-to-append-a-read-value-variable-to-a-file-which-has-double-quotes-in-it). – vintnes Jun 10 '19 at 09:05
  • Your file is invalid json. You're missing a comma after your InstanceType value. Like I said in the other thread, don't use `sed`, use `jq` – vintnes Jun 10 '19 at 09:08

2 Answers2

3

You can use light weight JSON processesor called jq

after loading your file you can use jq '.InstanceType = "This is instance value"

You can take reference from Add a new element to an existing JSON array using jq

Shivam Seth
  • 677
  • 1
  • 8
  • 21
2

use -e option will not modify the file instead it will print the output in terminal.

-i option will modify the file.

using .* regex will update the file and particular key having any value

and using \"\" will only look for empty string and update the value.

try this:

sed -i "s/\"InstanceType\":.*,$/\"InstanceType\": \"${instance_type}\",/g" awsspotinstancecreation.json

OR

sed -i "s/\"InstanceType\": \"\",$/\"InstanceType\": \"${instance_type}\",/g" awsspotinstancecreation.json

Vikash_Singh
  • 1,856
  • 2
  • 14
  • 27