【发布时间】:2016-08-17 20:24:47
【问题描述】:
我编写了一些脚本,它获取 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 脚本? 谢谢!
【问题讨论】:
-
文件是由什么生成的?它不是有效的 JSON;你应该解决这个问题并重新生成数据。
-
请提供一些示例输入。
-
@chepner 由于逗号,它不是有效的 json。这是我的问题。如何删除逗号?这个 shell 脚本在实例中安装包并从 local.json 获取变量。
-
要明确 - 我们将完全丢弃您当前的 shell 脚本,因为这是错误的方法。您需要发布样本的输入文件是您当前发布的 shell 脚本的输入。
-
我同意@EdMorton。手动构建 JSON 绝对是错误的开始方式。那里的许多语言,Perl、Ruby、Python 等,都有编写和测试良好的 JSON 模块,可以用几行代码构建你的 JSON。提供输入文件可能会为您提供强大且可扩展的解决方案。