I would like to write a variable to a JSON file.
I have tried many sed commands but still cant find a solution
#! bin/bash
echo "Hello"
echo "lets create an instance"
read -p "please enter the type of instance you need: " instance_type
echo $instance_type | sed -i "s|""InstanceType"": """"|""InstanceType"":
""${instance_type}""|g" awsspotinstancecreation.json
roxor@ubuntu:~$ bash rough.sh
Hello
lets create an instance
please enter the type of instance you need: t2.small
{
"ImageId": "ami-074acc26872f26463",
"KeyName": "Accesskeypair",
"SecurityGroupIds": ["sg-064caf9c470e4e8e6"],
**##"InstanceType": "${instance_type}",##**
"Placement": {
"AvailabilityZone": "us-east-1a"
}
}
Your
sed
has quoting issues as well as the problem of trying to read data from file and STDIN simultaneously.It's generally a bad idea to use line-oriented tools like
sed
,grep
, andawk
to parse or modify JSON. The best shell-based tool for this task isjq
.jq
1.5+:jq
1.4+:You can try using mustache. It is meant for exactly this purpose. Here is a bash implementation.
Picked from their site
Command
Output
It does not matter if the text is in JSON or just plain text as long as the delimiter is clear. Most implementations also give you an option to change the delimiter.