如何使用bash脚本向json文件添加json值

如何使用bash脚本向json文件添加json值,json,bash,shell,Json,Bash,Shell,Json文件如下所示: { "ImageId": "ami-074acc26872f26463", "KeyName": "Accesskeypair", "SecurityGroupIds": ["sg-064caf9c470e4e8e6"], "InstanceType": "" "Placement": { "AvailabilityZone": "us-east-1a" } } 从用户读取类型输入

Json文件如下所示:

{

      "ImageId": "ami-074acc26872f26463",
      "KeyName": "Accesskeypair",
      "SecurityGroupIds": ["sg-064caf9c470e4e8e6"],
      "InstanceType": ""
      "Placement": {
        "AvailabilityZone": "us-east-1a"
      }
}
从用户读取类型输入

现在,我想在InstanceType中添加json值:$type在文件中使用bash脚本,我已经尝试过sed、cat和echo
但当我这样做时,会出现InstanceType:$type而不是InstanceType:t2。small

您可以使用轻量级的JSON进程,或者称为jq

加载文件后,可以使用jq'.InstanceType=这是实例值


您可以参考

您可以使用轻量级JSON进程或jq

加载文件后,可以使用jq'.InstanceType=这是实例值

您可以参考

使用-e选项不会修改文件,而是在终端中打印输出

-i选项将修改该文件

使用.*regex将更新文件和具有任何值的特定密钥

并且使用\\将只查找空字符串并更新值

试试这个:

sed-i s/\InstanceType\:.*,$/\InstanceType\:\${instance\u type}\,/g awsspotinstancecreation.json

sed-i s/\InstanceType\:\,$/\InstanceType\:\${instance\u type}\,/g awsspotinstancecreation.json

使用-e选项不会修改文件,而是在终端中打印输出

-i选项将修改该文件

使用.*regex将更新文件和具有任何值的特定密钥

并且使用\\将只查找空字符串并更新值

试试这个:

sed-i s/\InstanceType\:.*,$/\InstanceType\:\${instance\u type}\,/g awsspotinstancecreation.json


sed-i s/\InstanceType\:\,$/\InstanceType\:\${instance\U type}\,/g awsspotinstancecreation.json

请返回并编辑您的文件。您的文件是无效的json。InstanceType值后缺少逗号。就像我在另一个线程中说的,不要使用sed,使用jqPlease返回并编辑您的文件。您的文件是无效的json。InstanceType值后缺少逗号。就像我在另一个线程中说的,不要使用sed,使用jqthanks a ton bro!!!它工作完美,谢谢你的解释。。。意味着很多!谢谢你,兄弟!!!它工作完美,谢谢你的解释。。。意味着很多!
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