how to append a read value variable to a file whic

2019-08-21 18:01发布

问题:

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"
      }
}

回答1:

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, and awk to parse or modify JSON. The best shell-based tool for this task is jq.

jq 1.5+:

read -p "Instance type: " instance
export instance
jq '.InstanceType=env.instance' awsspotinstancecreation.json

jq 1.4+:

read -p "Instance type: " instance
jq --arg instance "$instance" '.InstanceType=$instance' awsspotinstancecreation.json


回答2:

You can try using mustache. It is meant for exactly this purpose. Here is a bash implementation.

Picked from their site

Hello, {{NAME}}.

I hope your {{TIME_PERIOD}} was fun.

Command

NAME=Tyler TIME_PERIOD=weekend ./mo demo/fun-trip.mo

Output

Hello, Tyler.

I hope your weekend was fun.

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.



标签: bash shell