0

I need to write a script in AWK which will count all the files and their weight in "/home" directory from all the months and display the list in terminal. The output should look like this:

enter image description here

1
  • Are you an a system with a filesystem which keeps track of the birth time of a file? Some common filesystems does not do that. Commented Jan 27, 2019 at 13:29

1 Answer 1

0

I wrote script in awk which uses system commands ls to list files and stat to get info about file. After that script will print number of files and size in bytes.

#!/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]) } } 

Modify two things in this script:

  • dir = "/home/matej/" change your default directory
  • "stat --printf=\"%Y %s\" \"" dir filename "\"" | getline info use %W instead of %Y if your system supports time of birth

To run script:

  • chmod +x script.awk
  • ./script.awkor with argument ./script.awk /home/user

Output in my system looks like:

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 
0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.