從檔案名稱中的時間戳記日期中提取最高日期

從檔案名稱中的時間戳記日期中提取最高日期

檔案名稱的結構如下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

相關內容