AWK-列出特定月份创建的所有文件的数量和重量的脚本

AWK-列出特定月份创建的所有文件的数量和重量的脚本

我需要在 AWK 中编写一个脚本,该脚本将计算所有月份的“/home”目录中的所有文件及其权重,并在终端中显示列表。输出应如下所示:

在此输入图像描述

答案1

我在 awk 中编写了脚本,它使用系统命令ls列出文件并stat获取有关文件的信息。之后脚本将打印文件数量和大小(以字节为单位)。

#!/usr/bin/awk -f


BEGIN {
    dir = "/home/matej"   #chnage default directory

    if(ARGC == 2){   #check for command line arguments
        dir = ARGV[1]
    }
    printf("Listing directory: %s\n", dir)


    cmd = "ls " dir

    m_names[1] = "January"
    m_names[2] = "February"
    m_names[3] = "March"
    m_names[4] = "April"
    m_names[5] = "May"
    m_names[6] = "June"
    m_names[7] = "July"
    m_names[8] = "August"
    m_names[9] = "September"
    m_names[10] = "October"
    m_names[11] = "November"
    m_names[12] = "December"


    while((cmd | getline filename) > 0 ){
        "stat --printf=\"%Y %s\" \"" dir "/" filename "\"" | getline info   #use %W instead of %Y if your system supports date of birth
        #FS = " "
        split(info, arr, " ")
        time = arr[1]
        size = arr[2]

        month = strftime("%m", time) + 0   #+ 0 is for converting string to int and removein first 0

        months[month] = months[month] + 1
        sizes[month] = sizes[month] + size
    } 
    close(cmd)

    #pretty print
    printf("%-11s %-20.18s %s\n", "Month", "Number of files", "Total size of files (in bytes)")
    for(a = 1; a <= 12; a ++){
        printf("%-9s:   %-20s %s\n", m_names[a], months[a], sizes[a])
    }

}

修改此脚本中的两处内容:

  • dir = "/home/matej/"更改您的默认目录
  • "stat --printf=\"%Y %s\" \"" dir filename "\"" | getline info如果您的系统支持出生时间,请使用 %W 而不是 %Y

运行脚本:

  • chmod +x script.awk
  • ./script.awk或有论证./script.awk /home/user

我的系统中的输出如下所示:

Listing directory: /home/matej
month       number of files      total size of files
January  :   7                    163860
February :   1                    4096
March    :   1                    4096
April    :   1                    764
May      :   1                    4096
June     :   3                    12288
July     :   2                    13142852623
August   :   2                    8192
September:   1                    16
October  :   8                    10975459334
November :   4                    44067
December :   10                   49152

相关内容