Bash

從文件名中的時間戳日期中提取最高日

  • February 7, 2018

文件名的結構如下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

如果不使用文件時間戳,它會有點笨拙,但這是可以完成的一種方法:

#!/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

引用自:https://unix.stackexchange.com/questions/330626