我正在尝试将输入字符串与正则表达式模式匹配,如下所示:
formatDate(){
d='[[:digit:]]'
pattern_a="($d$d$d$d)($d$d)($d$d) ($d$d)($d$d)($d$d)"
pattern_b="($d$d$d$d)($d$d)($d$d)_($d$d)($d$d)($d$d)"
pattern_c="($d$d$d$d)($d$d)($d$d):($d$d)($d$d)($d$d)"
pattern_d="($d$d$d$d)($d$d)($d$d)($d$d)($d$d)($d$d)"
pattern_e="($d$d$d$d)($d$d)($d$d)($d$d)($d$d)($d$d)($d$d$d)"
unparsable_date="Unable to parse date!"
TM="TM"
appName="$1"
actionType="$2"
position="$3"
timestamp="$4"
shopt -s nocasematch
case "$position" in
"YYYYMMDD HHMMSS"|"YYYYMMDD_HHMMSS"|"YYYYMMDD:HHMMSS"|"YYYYMMDDHHMMSS"|"YYYYMMDDHHMMSSSSS")
if [[ $timestamp =~ $pattern_a|$pattern_b|$pattern_c|$pattern_d|$pattern_e ]]; then
formattedDate=${BASH_REMATCH[1]}${BASH_REMATCH[2]}${BASH_REMATCH[3]}
formattedTime=${BASH_REMATCH[4]}${BASH_REMATCH[5]}${BASH_REMATCH[6]}
formattedTimeStamp="$appName$actionType$formattedDate $appName$actionType$TM$formattedTime"
else
formattedTimeStamp=$unparsable_date
fi
;;
esac
}
如果我的输入符合$ pattern_a,则formattedTimeStamp
的值会正确填充,如下所示:
输入 - formatDate "appName" "actionType" "YYYYMMDD HHMMSS" "20170426 102300"
输出 - appNameactionType20170426 appNameactionTypeTM102300
在所有其他场景中,即与pattern_a之外的任何模式匹配,代码都不会产生正确的输出,
appNameactionType appNameactionTypeTM
"date and time is missing here "
感谢任何帮助!
答案 0 :(得分:0)
好吧,我用for循环替换了case语句。现在可以正常工作。
#!/bin/bash
d='[[:digit:]]'
pattern_a="($d$d$d$d)($d$d)($d$d) ($d$d)($d$d)($d$d)"
pattern_b="($d$d$d$d)($d$d)($d$d)_($d$d)($d$d)($d$d)"
pattern_c="($d$d$d$d)($d$d)($d$d):($d$d)($d$d)($d$d)"
pattern_d="($d$d$d$d)($d$d)($d$d)($d$d)($d$d)($d$d)"
pattern_e="($d$d$d$d)($d$d)($d$d)($d$d)($d$d)($d$d)($d$d$d)"
unparsable_date="Unable to parse date!"
TM="TM"
appName="appName"
actionType="actionType"
position="YYYYMMDD_HHMMSS"
timestamp="20170426_102300"
declare -a arr=( "$pattern_a" "$pattern_b" "$pattern_c" "$pattern_d" "$pattern_e")
for i in "${arr[@]}"
do
if [[ $timestamp =~ $i ]]; then
formattedDate=${BASH_REMATCH[1]}${BASH_REMATCH[2]}${BASH_REMATCH[3]}
formattedTime=${BASH_REMATCH[4]}${BASH_REMATCH[5]}${BASH_REMATCH[6]}
formattedTimeStamp="$appName$actionType$formattedDate $appName$actionType$TM$formattedTime"
echo $formattedTimeStamp
fi
done