json - 如何使用 Bash 删除 json 文件中的最后一个逗号?

标签 json bash shell awk sed

我写了一些脚本来获取 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/

相关文章:

php - 为什么对 json_encode 的 PHP 调用默默失败 - 无法处理单引号?

javascript - 如何在 Angular 2+ 中获取 json 数据

javascript - jQuery添加的反斜杠怎么去掉

bash - 为什么 bash 的手册页在写入文件时有双字母?

linux - 如何在脚本中自动说 2 以获得答案

c - 给出 5 个参数,但在终端中只得到 3 个参数

linux - 打包多个tar文件的Shell脚本(取决于日期)

node.js - 如何从json文件中读取和写入数据

macos - FFmpeg 3.3.4 avfoundation 使用命令行在 macOS Sierra 上仅记录屏幕的特定部分

node.js - 在 Node.js 之外设置全局环境变量