如何在linux中查找上个月修改的文件?

如何在linux中查找上个月修改的文件?

我需要在一个目录中查找上个月修改的文件并复制到另一个目录,但使用此命令我只能找到最近 31 天内修改的文件,而不是上个月修改的文件。

/usr/bin/find $SOURCE_DIR -maxdepth 1 -type f -name 'files*.pdf' -mtime -31 -exec cp -p {} $DEST_DIR`date +"%B_%Y"` \;

我需要上个月修改的文件,例如:一月、二月修改的文件,...有什么建议吗?

答案1

@SmileDeveloper 走在正确的轨道上,但事实证明它非常棘手:

$ cd "$(mktemp --directory)"
$ touch --date="$(date --date="$(date --rfc-3339=date | cut --characters=-7)-01 - 1 day" --rfc-3339=second)" last-day-of-last-month
$ touch --date="$(date --date="$(date --rfc-3339=date | cut --characters=-7)-01 - 1 second" --rfc-3339=second)" end-of-last-month
$ touch --date="$(date --rfc-3339=date | cut --characters=-7)-01" start-of-current-month
$ touch --date="$(date --date="$(date --rfc-3339=date | cut --characters=-7)-01 + 1 month - 1 second" --rfc-3339=second)" end-of-current-month
$ touch --date="$(date --date="$(date --rfc-3339=date | cut --characters=-7)-01 + 1 month" --rfc-3339=second)" start-of-next-month
$ stat --printf '%y\t%n\n' ./* | sort --key=1
2020-06-30 00:00:00.000000000 +1200 ./last-day-of-last-month
2020-06-30 23:59:59.000000000 +1200 ./end-of-last-month
2020-07-01 00:00:00.000000000 +1200 ./start-of-current-month
2020-07-31 23:59:59.000000000 +1200 ./end-of-current-month
2020-08-01 00:00:00.000000000 +1200 ./start-of-next-month
$ find . -mindepth 1 -newermt "$(date --rfc-3339=date | cut --characters=-7)-01 - 1 second" -not -newermt "$(date --rfc-3339=date | cut --characters=-7)-01 + 1 month - 1 second"
./end-of-current-month
./start-of-current-month

基本上,最后一个命令为您提供从上个月的最后一秒(不包括)到当月的最后一秒(包括)的范围。如果您想要绝对精度,可能会变得更加难看,因为find与大多数编程语言不同,似乎没有办法选择包含的开始日期时间和独占的结束日期时间。

希望您也不必担心时区问题!

答案2

当月(从第一天开始)

/usr/bin/find $SOURCE_DIR -maxdepth 1 -type f -name 'files*.pdf' -newermt "$(date +%y-%m-1)" -exec cp -p {} $DEST_DIR`date +"%B_%Y"` \;

上个月第一天至今:

/usr/bin/find $SOURCE_DIR -maxdepth 1 -type f -name 'files*.pdf' -newermt "$(date -d "$(date +%y-%m-1) - 1 month" +%y-%m-%d)" -exec cp -p {} $DEST_DIR`date +"%B_%Y"` \;

上个月第一天到上个月最后一天:

/usr/bin/find $SOURCE_DIR -maxdepth 1 -type f -name 'files*.pdf' -newermt "$(date -d "$(date +%y-%m-1) - 1 month" +%y-%m-%d)" -not -newermt "$(date +%y-%m-1)" \;

编辑:

不要使用mtime,因为mtime搜索在 中修改的文件24*n,并且不会在当天开始时开始。

答案3

我似乎用了find -printf很多这些东西。

$ which month_files
month_files () {
        find . -type f -printf "%TY-%Tm\t%p\n" | grep ^$1 | cut -f2
}

# example run on my ~/.cache directory
$ month_files 2020-05 | wc
   1007    1007   49917

现在您可以随心所欲地处理这些文件。例如,

mkdir /target/2020-05
month_files 2020-05 | xargs -d"\n" -I % cp % /target/2020-05/

强制(每行执行一次)。具体到命令,你可以使用以下方式来提高效率-I-L 1cp

month_files 2020-05 | xargs -d"\n" cp --target-directory /target/2020-05/

我假设所有文件名中都没有换行符。我并不真正支持我的系统上的这种废话,我的意思是空格和一些特殊字符是一回事,换行符是另一回事。 (或者,向伊恩·弗莱明道歉,“空间是偶然的;特殊字符是巧合,换行符是敌人的行动”!)

相关内容