Bash 从日期范围中选择名称中包含日期的目录
我正在创建一个目录列表,其名称中包含请求的日期范围 所有目录均标有“其他”字样,即2019-07-18T00-00-00。T把我搞砸了 从某处复制了这个循环Bash 从日期范围中选择名称中包含日期的目录,bash,date,directory,range,filenames,Bash,Date,Directory,Range,Filenames,我正在创建一个目录列表,其名称中包含请求的日期范围 所有目录均标有“其他”字样,即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
#!/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
我希望最终的回显包含匹配的所有目录的路径。日期和小时之间没有空格,这导致date无法读取日期。尝试:
sed 's/T/ /'
与AWK不同,Bash比较运算符而不是删除T。。。
好的,但是:
date -d 2019-03-23T00:06:28
Sat Mar 23 00:06:28 UTC 2019
因此,我们必须将最后两个破折号替换为::
由于您的问题被标记为bash:
这可以通过书面形式:
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+%s,并使用-f参数,date将解释每条输入线,然后回答UNIX_时间。因此,首先通过以下方式从日期进程读取$now:
echo now >&5 && # now, the string
read -u 6 now # read will populate `$now` variable
注意,一旦输入和输出打开fifo,它们就可以被删除。它将一直保留到进程关闭为止。当然,您在开始时间=…?@MarkSetchell号的行中缺少了一些分号。在这种赋值中不需要列。试试看!酷,这是有效的-虽然我不记得以前见过它,也不明白为什么:-我认为第一行printf-v现在。。。顺便说一句,它是bash4特有的。@MarkSetchell注意,我用斜杠时错了!回答正确!
date -d 2019-03-23T00:06:28
Sat Mar 23 00:06:28 UTC 2019
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
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>&-
echo now >&5 && # now, the string
read -u 6 now # read will populate `$now` variable