文件名的结构如下name$timestamp.extension
:
timestamp=`date "+%Y%m%d-%H%M%S"`
那么,如果目录中有以下文件:
name161214-082211.gz
name161202-082211.gz
name161220-082211.gz
name161203-082211.gz
name161201-082211.gz
随着您答案中的代码/脚本的执行,该值20
应存储在变量中highest_day
highest_day = 20
答案1
如果不使用文件时间戳,它会变得有点笨拙,但这是可以完成的一种方法:
#!/usr/bin/env bash
re="name([0-9]{6})-([0-9]{6})\.gz"
re2="([0-9]{2})([0-9]{2})([0-9]{2})"
for file in *.gz
do
if [[ "$file" =~ $re ]]
then
# BASH_REMATCH[n] on filename where n:
# [1] is date ie. 161202
# [2] is time ie. 082211
date=${BASH_REMATCH[1]}
# BASH_REMATCH[n] on date string where n:
# [1] is year ie. 16
# [2] is month ie. 12
# [3] is day ie. 02
[[ $date =~ $re2 ]] && day=${BASH_REMATCH[3]}
# Keep max day value
[[ $day > $highest_day ]] && highest_day=$day
fi
done
echo $highest_day
答案2
你可以这样做..
highest_day= $(for i in *.gz; do echo ${i:8:2}; done | sort -n | tail -1)
答案3
如果文件列表位于文件内,则类似于:
$ cd dir
$ ls -1 * >infile
该管道完成了工作:
$ sed 's/[^0-9]*\([0-9]*\)-.*/\1/' infile | sort -r | head -n1 | cut -c 5-6
20