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

标签 bash file ls

我有一个目录,每天都有文件。现在我想按日期压缩这些文件。无论如何,是否可以对同一日期登陆的文件进行分组/列出。

假设目录下有以下文件

-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

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

[ [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

最佳答案

如果您有 date 命令的 GNU 版本,您可以使用 -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 *

关于bash - 获取按日期分组的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40320815/

相关文章:

bash - POSIX 兼容的 shell 相当于 Bash "while read -d $'\0' ..."?

java - 文件夹不通过java程序在linux中创建

c - 文件中的字符数?

linux - 使用 ls -1 列出包含特定字符串并忽略特定字符串的文件

python - 为什么文件权限在 Python 和 bash 中显示不同?

c++ - system() 返回错误语法错误 : "(" unexpected

c - 如何正确从文件中读取结构?

bash - 计算目录中的总文件数 - find vs ls

Linux 列表文件差异 - "ls"与 "ls/"

linux - 如何确定逗号分隔字符串中字符串的顺序位置?