【问题标题】:how to append a read value variable to a file which has double quotes in it如何将读取值变量附加到其中包含双引号的文件
【发布时间】:2019-06-10 05:24:39
【问题描述】:

我想将一个变量写入 JSON 文件。

我尝试了许多 sed 命令,但仍然找不到解决方案

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

【问题讨论】:

  • 您好,请提供minimal reproducible example。这意味着样本 json 输入和样本所需的 json 输出。第三,它现在做了什么(所以失败的 JSON 结果)。另请查看 StackOverflow 的帮助页面,并了解如何使用编辑器来格式化您的问题。照原样,它是不可读的。

标签: bash shell


【解决方案1】:

您的sed 存在引用问题以及尝试同时从文件和 STDIN 读取数据的问题。

使用sedgrepawk 等面向行的工具来解析或修改JSON 通常是个坏主意。这个任务最好的基于 shell 的工具是jq

jq1.5+:

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

jq1.4+:

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

【讨论】:

  • 我收到此错误解析错误:第 6 行第 14 列值之间的预期分隔符
  • @shrikkanthroxor 请更新您的问题以包含实际的 awsspotinstancecreation.json 文件
【解决方案2】:

您可以尝试使用mustache。它正是为了这个目的。这是一个bash 实现。

从他们的网站挑选

Hello, {{NAME}}.

I hope your {{TIME_PERIOD}} was fun.

命令

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

输出

Hello, Tyler.

I hope your weekend was fun.

只要分隔符清晰,文本是 JSON 格式还是纯文本格式都没有关系。大多数实现还为您提供更改分隔符的选项。

【讨论】:

  • 这比 here-doc 有什么优势?
  • 不知道为什么要比较。我经常使用 mustache 进行去模板化,这就是这里正在做的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 2018-09-02
相关资源
最近更新 更多