我写了一些脚本来获取 aws ec2 实例的所有用户数据,并回显到 local.json。当我安装我的 node.js 模块时,所有这些都会发生。 我不知道如何删除 json 文件中的最后一个逗号。这是 bash 脚本:
#!/bin/bash
export DATA_DIR=/data
export PATH=$PATH:/usr/local/bin
#install package from git repository
sudo -- sh -c "export PATH=$PATH:/usr/local/bin; export DATA_DIR=/data; npm install git+https://reader:secret@bitbucket.org/somebranch/$1.git#$2"
#update config files from instance user-data
InstanceConfig=`cat /instance-config`
echo '{' >> node_modules/$1/config/local.json
while read line
do
if [ ! -z "$line" -a "$line" != " " ]; then
Key=`echo $line | cut -f1 -d=`
Value=`echo $line | cut -f2 -d=`
if [ "$Key" = "Env" ]; then
Env="$Value"
fi
printf '"%s" : "%s",\n' "$Key" "$Value" >> node_modules/*/config/local.json
fi
done <<< "$InstanceConfig"
sed -i '$ s/.$//' node_modules/$1/config/local.json
echo '}' >> node_modules/$1/config/local.json
要运行他,我就是这样做的:./script 我得到 json(OUTPUT),但所有行中都带有逗号。这是我得到的 local.json:
{
"Env" : "dev",
"EngineUrl" : "engine.url.net",
}
我想做的就是删除 json 文件的最后一行 - 逗号 (",")。 我尝试了很多方法,我在互联网上找到了。我知道它应该在最后一个“fi”(循环结束)之后。我知道它应该是这样的:
sed -i "s?${Key} : ${Value},?${Key} : ${Value}?g" node_modules/$1/config/local.json
或者这个:
sed '$ s/,$//' node_modules/$1/config/local.json
但它们对我不起作用。 有人可以帮我吗?谁非常了解 Bash 脚本? 谢谢!
最佳答案
如果您知道需要替换的是最后一个逗号,一个相当稳健的方法是以“slurp”模式使用 GNU sed,如下所示:
sed -zr 's/,([^,]*$)/\1/' local.json
输出:
{
"Env" : "dev",
"EngineUrl" : "engine.url.net"
}
关于json - 如何使用 Bash 删除 json 文件中的最后一个逗号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36823741/