从日期范围中选择名称中带有日期的目录

时间:2019-07-25 05:53:43

标签: bash date directory range filenames

我正在创建目录列表,其名称中包含请求的日期范围。

目录都标记为other_2019-07-18T00-00-00 T 弄乱了我!

从某个地方复制了此循环。

#!/bin/bash
curdate=$(date +%Y-%m-%d%H-%M-%S)
#
for o in other_*; do
    tmp=${o##other_}
      tmp=$(echo "$tmp" | sed 's/T//') # clean up prefixes
      fdate=$(date -d "${tmp}")
      (( curdate < fdate )) && echo "$o"
done

我希望最后一个echo包含所有匹配目录的路径。

3 个答案:

答案 0 :(得分:1)

AWK不同,Bash比较运算符<仅适用于数值。
请尝试:

#!/bin/bash
curdate=$(date +%Y%m%d%H%M%S)

for o in other_*; do
    tmp=${o##other_}
    fdate=$(echo "$tmp" | sed 's/[-T]//g')  # numeralization
    (( curdate < fdate )) && echo "$o"
done

作为替代方案,您可以比较纪元时间:

#!/bin/bash

curdate=$(date +%s)

for o in other_*; do
    tmp=${o##other_}
    tmp=$(echo "$tmp" | sed 's/T/ /' | sed 's/\([0-9][0-9]\)-\([0-9][0-9]\)-\([0-9][0-9]\)$/\1:\2:\3/')
    fdate=$(date -d "$tmp" +%s)
    (( curdate < fdate )) && echo "$o"
done

希望这会有所帮助。

答案 1 :(得分:1)

与其删除T ...

date -d 2019-03-23T00-06-28
date: invalid date '2019-03-23T00-06-28'

好的,但是:

date -d 2019-03-23T00:06:28
Sat Mar 23 00:06:28 UTC 2019

所以我们必须用:代替最后两个破折号:

您的问题被标记为bash:

file="somepath/other_2019-07-18T00-00-00.extension"
time=${file#*other_}    # suppress from left until 'other_'
time=${time%.*}         # suppress extension
time=${time//-/:}       # replace all dash by a `:`
time=${time/:/-}        # replace 1nd `:` by a dash
time=${time/:/-}        # replace 1nd `:` by a dash (again)
date -d $time
Thu Jul 18 00:00:00 UTC 2019

可以这样写:

printf -v now "%(%s)T" -1         # bashism for current date to variable $now
for file in somepath/other_*.ext ;do
    time=${file#*other_} time=${time%.*} time=${time//-/:}
    time=${time/:/-} time=${time/:/-}
    read fdate < <(date +%s -d $time)
    ((fdate > now)) && { echo $file: $((fdate - now)) ; }
done        

减少叉子(到date)提高了速度:

为匹配样本,您可以将for file in somepath/other_*.ext ;do替换为for file in other_*; do。这必须完全相同。

fifo=/tmp/fifo-date-$$
mkfifo $fifo
exec 5> >(exec stdbuf -o0 date -f - +%s >$fifo 2>&1)
echo now 1>&5
exec 6< $fifo
read -t 1 -u 6 now
rm $fifo
for file in otherdates/*.ext ; do
    time=${file#*other_} time=${time%.*} time=${time//-/:}
    time=${time/:/-} time=${time/:/-}
    echo $time 1>&5 && read -t 1 -u 6 fdate
    ((fdate > now)) && { 
        echo $file: $((fdate - now))
    }
done
exec 6>&-
exec 5>&-

在这种情况下,我在后台运行date +%s,并使用-f参数,date将解释每行输入,然后回答 UNIX_TIME 。因此,首先通过以下方式从$now流程中读取date

echo now >&5 &&        # now, the string
    read -u 6 now      # read will populate `$now` variable

注意,输入和输出同时打开 fifo 时,可以将其删除。它将保留给进程,直到进程关闭它们。

答案 2 :(得分:0)

白天和小时之间没有空格,导致date无法读取日期。试试:

sed 's/T/ /'