7

我正在尝试创建一个脚本,它将以 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 对象之间缺少逗号。如何在命令中添加它?

4

1 回答 1

9
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 " ] " }
'

第一次通过时,分隔符变量为空,然后将其分配给第二行。

于 2013-06-06T23:52:31.023 回答