本文介绍了如何将读取值变量附加到其中带有双引号的文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将变量写入JSON文件.
I would like to write a variable to a JSON file.
我尝试了许多sed命令,但仍然找不到解决方法
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"
}
}
推荐答案
您的 sed
存在引用问题以及试图同时从文件和STDIN读取数据的问题.
Your sed
has quoting issues as well as the problem of trying to read data from file and STDIN simultaneously.
使用面向行的工具(例如 sed
, grep
和 awk
)来解析或修改JSON通常是一个坏主意.最好的基于shell的工具是 jq
.
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
这篇关于如何将读取值变量附加到其中带有双引号的文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!