使用日期作为文件名并将输出作为数组查找文件范围



我有一个名为的文件列表

2020-01-02.csv
2020-01-03.csv

等等,但有些日子不会生成这些。 由于时区和其他原因,我无法使用系统时间戳来创建/修改,因为它们会延续到第二天。

我基本上需要能够指定 2 个日期范围(开始和结束(作为变量,然后将找到的文件列表输出到数组中。

我尝试过使用它,如果文件存在,它可以工作,但如果文件不存在,它会失败并且不输出任何内容

$ find -type f -newer 2020-01-02.csv ! -newer 2020-01-14.csv
find: '2020-01-07.csv': No such file or directory

但如果我这样做

find -type f -newer 2020-01-02.csv ! -newer 2020-01-03.csv

我得到以下输出:

./2020-01-02.csv
./2020-01-03.csv

有很多方法。首先是使用文件名:

todate=$(date -d 2019-07-18 +%s)
fromdate=$(date -d 2017-08-19 +%s)
for file in *.csv ; do
filename=${file%.csv}
filedate=$(date -d $filename +%s)
if [ $filedate -ge $fromdate ] ; then
if [ $filedate -le $todate ] ; then
echo "Hurray for $file"
fi
fi
done

您可以压缩代码,但为了清楚起见,我写得有点冗长。

另一种方法是使用文件的时间戳:

for file in *.csv ; do
filename=${file%.csv}
timestamp=${filename//-/}
touch -t $timestamp $file
done
touch -t fromfile 2020010200
touch -t tofile   2020011400
find -type f -newer fromfile ! -newer tofile

考虑将"查找"管道传输到"awk"执行过滤。

如果所有文件都在同一文件夹中,则可以将find ...替换为ls *.csv

对于大量文件,对每个文件调用date可能会很慢。使用 find/awk 通常会快得多。

awk单行将文件拆分为基于"/"(-F/(的组件,而不是过滤最后一个组件($NF(

#! /bin/bash
from=2017-07-18
last=2019-07-18
find . -name '*.csv' |
awk -F/ -v FROM="$from" -v LAST="$last" 'match($NF, "^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]\.csv") && $NF >= FROM && $NF <= LAST''

最新更新