Get list of files group by Date

filesls

I have a directory with files coming for every day. Now I want to zip those files group by dates. Is there anyway to group/list the files which landed in same date.

Suppose there are below files in a directory

-rw-r--r--. 1 anirban anirban    1598 Oct 14 07:19 hello.txt
-rw-r--r--. 1 anirban anirban    1248 Oct 14 07:21 world.txt
-rw-rw-r--. 1 anirban anirban  659758 Oct 14 11:55 a
-rw-rw-r--. 1 anirban anirban    9121 Oct 18 07:37 b.csv
-rw-r--r--. 1 anirban anirban     196 Oct 20 08:46 go.xls
-rw-r--r--. 1 anirban anirban    1698 Oct 20 08:52 purge.sh
-rw-r--r--. 1 anirban anirban   47838 Oct 21 08:05 code.java
-rw-rw-r--. 1 anirban anirban 9446406 Oct 24 05:51 cron
-rw-rw-r--. 1 anirban anirban  532570 Oct 24 05:57 my.txt
drwxrwsr-x. 2 anirban anirban      67 Oct 25 05:05 look_around.py
-rw-rw-r--. 1 anirban anirban   44525 Oct 26 17:23 failed.log

So there are no way to group the files with any suffix/prefix, since all are unique. Now when I will run the command I am seeking I will get a set of lines like below based on group by dates.

[ [hello.txt world.txt a] [b.csv] [go.xls purge.sh] [code.java] ... ] and so on.

With that list I will loop through and make archive

tar -zvcf Oct_14.tar.gz hello.txt world.txt a

Best Answer

With zsh, using an associative array whose keys are the dates and values the NUL-delimited list of files last modified on that date:

zmodload -F zsh/stat b:zstat
typeset -A files
for file (./*) {
  zstat -LA date -F %b_%d +mtime $file &&
    files[$date]+=$file$'\0'
}
for date (${(k)files})
  echo tar zcvf $date.tar.gz ${(0)files[$date]}

Remove the echo when happy.

Note that the month name abbreviations (%b strftime format) will be in the current locale's language (Oct on an English system, Okt on a German one, etc.). To always make it English names regardless of the user's locale, force the locale to C with LC_ALL=C zstat....

With GNU tools, you could do the equivalent with:

find . ! -name . -prune ! -name '.*' -printf '%Tb_%Td:%p\0' |
  awk -v RS='\0' -F : -v q=\' '
    function quote(s) {
      gsub(q, q "\\" q q, s)
      return q s q
    }
    {
      date=$1
      sub(/[^:]*:/, "", $0)
      files[date] = files[date] " " quote($0)
    }
    END {
      for (date in files)
        print "tar zcvf " quote(date ".tar.gz") files[date]
    }'

Pipe to sh when happy.

Related Question