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"

2
  • 1
    Please go back and edit your original question. Commented Jun 10, 2019 at 9: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 Commented Jun 10, 2019 at 9:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

thanks a ton bro !!! it works perfectly and thanks for the explanation... means alot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.