bash Awk:将输出格式化为 json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16972804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Awk: Formatting output as json
提问by devang
I am trying to create a script that will return disk usage for a machine in json format. Here's the command -
我正在尝试创建一个脚本,该脚本将以 json 格式返回机器的磁盘使用情况。这是命令——
df -k | grep -v Filesystem | gawk 'BEGIN { ORS = ""; print " [ "} {printf " { \"name\" : \"""\", \"usage\" : \"""\", \"mount_point\" : \"""\" }" } END { print " ] " }'`
The output obtained is -
获得的输出是 -
[ { "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" } ]
If you observe, there is a comma missing between two json objects. How to I add this in the command?
如果您观察到,两个 json 对象之间缺少逗号。如何在命令中添加这个?
回答by glenn Hymanman
df -k | gawk '
BEGIN { ORS = ""; print " [ "}
/Filesystem/ {next}
{ printf "%s{\"name\": \"%s\", \"usage\": \"%s\", \"mount_point\": \"%s\"}",
separator, , ,
separator = ", "
}
END { print " ] " }
'
The first time through, the separator variable is empty, then it gets assigned for the second line.
第一次通过,分隔符变量为空,然后它被分配给第二行。

