Pet*_*ill 12 osx bash timestamps files
我YYYYMMDD在文件名中有一个名为 with的文件,例如
file-name-20151002.txt
Run Code Online (Sandbox Code Playgroud)
我想确定这个文件是否在 2015-10-02 之后被修改过。
ls,但我知道解析 的输出ls是一个坏主意。20151002名称中的文件是否在 2015 年 10 月 3 日或之后被修改过。以下脚本将检查命令行上指定的所有文件的日期:
它需要的GNU版本sed,date和stat
$ cat check-dates.sh
#! /bin/bash
for f in "$@" ; do
# get date portion of filename
fdate=$(basename "$f" .txt | sed -re 's/^.*(2015)/\1/')
# convert it to seconds since epoch + 1 day
fsecs=$(echo $(date +%s -d "$fdate") + 86400 | bc )
# get modified timestamp of file in secs since epoch
ftimestamp=$(stat -c %Y "$f")
[ "$ftimestamp" -gt "$fsecs" ] && echo "$f has been modified after $fdate"
done
$ ./check-dates.sh file-name-20151002.txt
file-name-20151002.txt has been modified after 20151002
$ ls -l file-name-20151002.txt
-rw-rw-r-- 1 cas cas 0 Oct 26 19:21 file-name-20151002.txt
Run Code Online (Sandbox Code Playgroud)
这是一个未经测试的版本,但如果我正确阅读了在线手册页,它应该可以在 Mac(以及 FreeBSD 等)上运行:
#! /bin/bash
for f in "$@" ; do
# get date portion of filename
fdate=$(basename "$f" .txt | sed -e 's/^.*\(2015\)/\1/')
# convert it to seconds since epoch + 1 day
fsecs=$(echo $(date -j -f %Y%m%d "$fdate" +%s) + 86400 | bc )
# get modified timestamp of file in secs since epoch
ftimestamp=$(stat -f %m "$f")
[ "$ftimestamp" -gt "$fsecs" ] && echo "$f has been modified after $fdate"
done
Run Code Online (Sandbox Code Playgroud)
以下是一些可能的方法:
OSX stat:
newer () {
tstamp=${1:${#1}-12:8}
mtime=$(stat -f "%Sm" -t "%Y%m%d" "$1")
[[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"
}
Run Code Online (Sandbox Code Playgroud)GNU date:
newer () {
tstamp=${1:${#1}-12:8}
mtime=$(date '+%Y%m%d' -r "$1")
[[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"
}
Run Code Online (Sandbox Code Playgroud)zsh仅有的:
zmodload zsh/stat
newer () {
tstamp=${1:${#1}-12:8}
mtime=$(zstat -F '%Y%m%d' +mtime -- $1)
[[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"
}
Run Code Online (Sandbox Code Playgroud)用法:
较新的文件
输出示例:
file-name-20150909.txt : YES: mtime is 20151026
Run Code Online (Sandbox Code Playgroud)
或者
file-name-20151126.txt : NO: mtime is 20151026
Run Code Online (Sandbox Code Playgroud)