假设(D.M.YYYY),从两个不同格式的日期生成正则表达式时间范围(YYYYMMDD)的最佳方法是什么?例如,三种不同的情况:
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]"或者,有没有更好的regexp来获得相同的结果,而不是“想要的结果”在当前表单中实现的结果?一个星期就足够了,不需要超过30天。
发布于 2012-11-07 17:28:17
考虑到您的范围很小(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|20120204https://stackoverflow.com/questions/13265487
复制相似问题