简体   繁体   English

使用“ du”输出JSON监视CentOS中的磁盘使用情况

[英]Monitoring disk usage in CentOS using 'du' to output JSON

I want to write a line of code which will take the results of: 我想写一行代码,其结果如下:

du -sh -c --time /00-httpdocs/*

and output it in JSON format. 并以JSON格式输出。 The goal is to get three pieces of information for each project file in a site: directory path, date last modified, and disk space usage in human readable format. 目的是为站点中的每个项目文件获取三段信息:目录路径,上次修改日期以及人类可读格式的磁盘空间使用情况。 This command will output that data in tab-delimited format with each entry on a new line in the terminal: 此命令将以制表符分隔的格式输出该数据,并在终端中的新行上显示每个条目:

4.6G    2014-08-22 12:26    /00-httpdocs/00
1.1G    2014-08-22 13:32    /00-httpdocs/01
711M    2014-02-14 23:39    /00-httpdocs/02

The goal is to get it to export to a JSON file so it would need to be formatted something like this: 目标是使其导出到JSON文件,因此需要将其格式化为以下格式:

{"httpdocs": [
  {
    "size": "4.6G",
    "modified": "2014-08-22 12:26",
    "path": "/00-httpdocs/00-PREVIEW"}
  {
    "size": "1.1G",
    "modified": "2014-08-22 13:32",
    "path": "/00-httpdocs/8oclock"}
  {
    "size": "711M",
    "modified": "2014-02-14 23:39",
    "path": "/00-httpdocs/8oclock.new"}
]}

(I know that's not quite proper JSON, I just wrote it as an example. Apologies to the pedantic among us.) (我知道那不是很合适的JSON,我只是写了一个例子。对我们中间的学徒表示歉意。)

I need size to return as an integer (so maybe remove '-sh' and handle conversion later?). 我需要大小以整数形式返回(因此也许删除“ -sh”并稍后处理转换?)。

I've tried using awk and sed but I'm a total novice and can't quite get the formatting right. 我尝试使用awk和sed,但是我是一个新手,不能完全正确地设置格式。

I've made it about this far: 我到目前为止已经做到了:

du -sh -c --time /00-httpdocs/* | awk ' BEGIN {print "\"httpdocs:\": [";} {print "{"$0"},\n";} END {print "]";}'

The goal is to have this trigger twice a day so that we can get the data and use it inside of a JavaScript application. 目标是每天触发两次,以便我们可以获取数据并在JavaScript应用程序中使用它。

sed '1 i\
{"httpdocs": [
s/\([^[:space:]]*\)([[:space:]]*\([^[:space:]]*\)[[:space:]]*\([^[:space:]]*\)/  {\
    "size" : "\1",\
    "modified": "\2",\
    "path": "\3"}/
$ a\^J]}' YourFile

Quick and dirty (posix version so --posix on GNU sed). 快速又肮脏(posix版本是GNU sed上的--posix )。

Take the 3 argument and place them ( s/../../ ) into a 'template" using group ( \\( ...\\) and \\1 ). Include header at 1st line ( i \\... ) and append footer ant last ( a \\... ). [:space:] may be [:blank:] 使用3参数并将它们( s/../../ )使用组( \\( ...\\)\\1 )放入“模板”中。在第一行( i \\... )包括标头最后添加页脚蚂蚁( a \\... )。 [:space:]可能是[:blank:]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM