获取按日期分组的文件列表

Get list of files group by Date

我有一个目录,每天都有文件。现在我想按日期压缩这些文件。无论如何 group/list 在同一日期登陆的文件。

假设目录中有以下文件

-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

因此无法将文件与 suffix/prefix 分组,因为所有文件都是唯一的。现在,当我 运行 我正在寻找的命令时,我将根据日期分组得到一组如下所示的行。

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

有了这个列表,我将遍历并制作存档

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

如果你有 GNU 版本的 date 命令,你可以用 -r 标志获取文件的修改日期,这非常有用。 例如,给定您问题中的文件列表,date +%b_%d -r hello.txt 将输出 Oct_14.

使用它,您可以遍历文件,并构建 tar 个文件:

  • 如果 tar 文件不存在,请使用单个文件创建它
  • 如果 tar 文件存在,将文件添加到其中
  • 循环后,压缩 tar 个文件

像这样:

#!/usr/bin/env bash

tarfiles=()

for file; do
    tarfile=$(date +%b_%d.tar -r "$file")
    if ! [ -f "$tarfile" ]; then
        tar cf "$tarfile" "$file"
        tarfiles+=("$tarfile")
    else
        tar uf "$tarfile" "$file"
    fi
done

for tarfile in "${tarfiles[@]}"; do
    gzip "$tarfile"
done

将要存档的文件列表作为命令行参数传递,例如,如果 /path/to/files 是您要存档文件的目录(在您的问题中列出),并且您将此脚本保存在 ~/bin/tar-by-dates.sh,那么你可以这样使用:

cd /path/to/files
~/bin/tar-by-dates.sh *

创建 (Month_Day.tar FILENAME) 对的零分隔列表并使用 xargs 将每个文件添加到相应的归档:

find . -maxdepth 1 -mindepth 1 -type f -printf "%Tb%Td.tar[=10=]%f[=10=]"|xargs -n 2 -0 tar uf