首页 > 解决方案 > 使用 shell 绘制总文件数和创建日期的图表

问题描述

我想创建一个直方图,Y 轴上的总文件计数间隔为 50,X 轴上以周为单位创建时间(即,如果在第 1 周和第 2 周之间创建新文件,依此类推)

就像是

200, 150, 100, 50 个文件在 Y 轴上的某个周 7、14、21、28 天创建。有点迷失了如何实现这一点。任何帮助表示赞赏

更新:我正在尝试这些方面

find <dirname> -type f -ctime -1 -ctime -7 | wc -l
find <dirname> -type f -ctime +7 -ctime -14 | wc -l

找到最大数字并将其用作我的 X 轴上限。然后将这个数字分成相等的间隔来绘制我的 X 轴

标签: linuxbashshellawkcsh

解决方案


这是将 GNU awk 用于时间函数的开始(未经测试,因为您没有提供我们可以测试的简洁、可测试的示例输入):

find "$1" -type f -printf '%T@ %p\0' |
awk -v RS='\0' '
BEGIN {
    nowSecs = systime()
}
{
    fileName     = gensub(/\S+\s+/,"",1)
    fileModSecs  = int($1)
    fileAgeSecs  = nowSecs - fileModSecs
    fileAgeDays  = int(fileAgeSecs / (24 * 60 * 60))
    fileAgeWeeks = int(fileAgeDays / 7)
    weekNr       = fileAgeWeeks + 1
    fileCnts[weekNr]++
    numWeeks     = (weekNr > numWeeks ? weekNr : numWeeks)
    maxFileCnt   = (fileCnts[weekNr] > maxFileCnt ? fileCnts[weekNr] : maxFileCnt)
    print nowSecs, fileModSecs, fileAgeSecs, fileAgeDays, fileAgeWeeks, weekNr, fileName | "cat>&2"
}
END {
    for (fileCnt=maxFileCnt; fileCnt>0; fileCnt--) {
        for (weekNr=1; weekNr<=numWeeks; weekNr++) {
            if (weekNr in fileCnts) {
                char[weekNr] = "*"
            }
            printf "%s%s", char[weekNr], (weekNr<numWeeks ? OFS : ORS)
        }
    }
    for (weekNr=1; weekNr<=numWeeks; weekNr++) {
        printf "%s%s", weekNr, (weekNr<numWeeks ? OFS : ORS)
    }
}
'

您需要在 END 部分中找出循环的详细信息以打印直方图,但上面至少向您展示了如何按周获取文件数,而无需多次调用 find 并逐周硬编码天数.


推荐阅读