Linux

AWK- 列出特定月份創建的所有文件的數量和權重的腳本

  • January 27, 2019

我需要在 AWK 中編寫一個腳本,它將計算所有月份在“/home”目錄中的所有文件及其權重,並在終端中顯示列表。輸出應如下所示:

在此處輸入圖像描述

我在 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

引用自:https://unix.stackexchange.com/questions/496993