2012-11-07 14 views
1

從不同格式的兩個日期生成正則表達式時間範圍(YYYYMMDD)的最佳方法是什麼?假設(D.M.YYYY)?例如,三個不同的情況:從兩個日期生成正則表達式時間戳範圍

input date 1 = "20.11.2012" 
input date 2 = "27.11.2012" 
Wanted result = "2012112[0-7]" 

input date a = "31.12.2011" 
input date b = "6.1.2012" 
Wanted result = "20111231\\|2012010[1-6]" 

input date x = "28.1.2012" 
input date y = "4.2.2012" 
Wanted result = "2012012[8-9]\\|2012013[0-1]\\|2012020[1-4]" 

或者是有變得比什麼「通緝的結果」,在目前的形式達到相同的結果更好的正則表達式?一週就足夠了,而且不需要超過30天。

+0

你應該嘗試使用的strftime使用awk例如。 – Zulu

回答

1

鑑於您的範圍很小(7天),簡單地生成所有日期會容易得多。

這裏是一個腳本來做到這一點:

#!/bin/bash 
fromDate="$1" 
toDate="$2" 

# break the dates into array so that we can easily access the day, month and year 
IFS='.' read -a fromDateParts <<< "$fromDate" 
IFS='.' read -a toDateParts <<< "$toDate" 

# loop until the days, months and years match on both dates 
while [[ "${toDateParts[0]}" -ne "${fromDateParts[0]}" || "${toDateParts[1]}" -ne "${fromDateParts[1]}" || "${toDateParts[2]}" -ne "${fromDateParts[2]}" ]] 
do 
    # add the date to the pattern 
    printf -v date "%d%02d%02d" "${fromDateParts[2]}" "${fromDateParts[1]}" "${fromDateParts[0]}" 
    pattern="$pattern|$date" 

    ((fromDateParts[0]++)) 

    # reset days and increment month if days exceed 31 
    if [[ "${fromDateParts[0]}" -gt 31 ]] 
    then 
     fromDateParts[0]=1 
     ((fromDateParts[1]++)) 

     # reset month and increment year if months exceed 12 
     if [[ "${fromDateParts[1]}" -gt 12 ]] 
     then 
      fromDateParts[1]=1 
      ((fromDateParts[2]++)) 
     fi 
    fi 
done 

# finally add the toDate to the pattern 
printf -v date "%d%02d%02d" "${toDateParts[2]}" "${toDateParts[1]}" "${toDateParts[0]}" 
pattern="$pattern|$date" 

# print the pattern, removing the first pipe 
echo "${pattern#?}" 

實例應用:

$ dateRange.sh 28.1.2012 4.2.2012 
20120128|20120129|20120130|20120131|20120201|20120202|20120203|20120204 

$ dateRange.sh 31.12.2011 6.1.2012 
20111231|20120101|20120102|20120103|20120104|20120105|20120106 

$ dateRange.sh 28.1.2012 4.2.2012 
20120128|20120129|20120130|20120131|20120201|20120202|20120203|20120204