json - shell脚本从一个文件中读取值并将其替换为另一个文件

标签 json linux bash shell heredoc

我想将一组字符串替换到一个新文件中。必须将源文件 file1.json 的值替换为文件 file2.json 中 file1.config 中的值。我有以下脚本未能这样做。

file1.json

{
    "colorsArray":[{
            "red":"$ALERT_LEVEL",
            "green":"$NORMAL_LEVEL",
            "blue":"$RELAX_LEVEL"
        }
    ]
}

file1.config

[root@ip10]# cat file1.config
ALERT_LEVEL=DANGER
NORMAL_LEVEL=NORMAL
RELAX_LEVEL=RELAX

运行.sh

    #!/bin/bash
set -x
if [ $# -ne 3 ]; then
  echo "USAGE:
        ./$0 file1.json file2.json file1.config"
  exit 1
fi
echo "#!/bin/bash
cat > $2 << EOF
`cat $1`
EOF" > $2;
chmod +x $2;
# load variables into env
. $3
# actually replace variables
./$2

错误:

[root@ip10]# ./run2.sh file1.json file2.json file1.config
./file2.json: line 11: warning: here-document at line 2 delimited by end-of-file (wanted `EOF')

file2.json 出现,但没有替换任何值。

root@ip10]# cat file2.json 
    {
        "colorsArray":[{
                "red":"",
                "green":"",
                "blue":""
            }
        ]
    }

最佳答案

只是解释@user3159253 的评论。你的 file1.config 应该看起来像这样你的代码才能正常工作:

export ALERT_LEVEL=DANGER
export NORMAL_LEVEL=NORMAL
export RELAX_LEVEL=RELAX

附言恕我直言,你做这件事的方式有点过于复杂。我更喜欢使用 sed 来完成这个任务——只需要一个字符串:

sed file1.json -e 's/$ALERT_LEVEL/DANGER/g' -e's/$NORMAL_LEVEL/NORMAL/g' -e's/$RELAX_LEVEL/RELAX/g' >file2.json

关于json - shell脚本从一个文件中读取值并将其替换为另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34705062/

相关文章:

json - Perl Json 编码有 float 的引号

linux - Ubuntu中Mit Scheme安装错误(环境变量设置)

Bash脚本,while循环中的多个条件

ruby-on-rails - 如何检查docker容器内的ruby版本

linux - 用于从 Postgresql 中获取行的 Bash 脚本

java - 安卓/乱舞 : Unable to instantiate activity component?

ios - 如何将数据加载到 TableView 中

java - 将内部 JSON 对象提取为 Jackson 中的 String

linux - 如何跟踪 EC2 实例或弹性 IP 上的公共(public)带宽使用情况?

php - Composer(php的库管理器)生成的vendor目录在linux和windows中是否相同?