Awk:将输出格式化为json

时间:2013-06-06 21:51:39

标签: bash awk

我正在尝试创建一个脚本,该脚本将以json格式返回计算机的磁盘使用情况。这是命令 -

df -k $1 | grep -v Filesystem | gawk 'BEGIN { ORS = ""; print " [ "} {printf " { \"name\" : \""$1"\", \"usage\" : \""$5"\", \"mount_point\" : \""$6"\" }" } END { print " ] " }'`

获得的输出是 -

 [  { "name" : "/dev/sda4", "usage" : "36%", "mount_point" : "/" } { "name" : "udev", "usage" : "1%", "mount_point" : "/dev" } { "name" : "tmpfs", "usage" : "0%", "mount_point" : "/dev/shm" } { "name" : "/dev/sda1", "usage" : "17%", "mount_point" : "/boot" }  ]

如果观察,两个json对象之间缺少逗号。如何在命令中添加它?

1 个答案:

答案 0 :(得分:6)

df -k $1  | gawk '
    BEGIN { ORS = ""; print " [ "}
    /Filesystem/ {next}
    { printf "%s{\"name\": \"%s\", \"usage\": \"%s\", \"mount_point\": \"%s\"}",
          separator, $1, $5, $6
      separator = ", "
    }
    END { print " ] " }
'

第一次,分隔符变量为空,然后为第二行分配。