linux shell實現(xiàn)轉(zhuǎn)換輸入日期的格式
對于用戶輸入日期的合法性檢驗,是個很重要的問題,這個例子是簡單得取得用戶輸入的日期,并轉(zhuǎn)換為相應(yīng)的格式,但不完美,原因請看后文。
#!/bin/sh
# normdate -- Normalizes month field in date specification
# to three letters, first letter capitalized. A helper
# function for Script #7, valid-date. Exits w/ zero if no error.
monthnoToName()
{
# Sets the variable 'month' to the appropriate value
case $1 in
1 ) month="Jan" ;; 2 ) month="Feb" ;;
3 ) month="Mar" ;; 4 ) month="Apr" ;;
5 ) month="May" ;; 6 ) month="Jun" ;;
7 ) month="Jul" ;; 8 ) month="Aug" ;;
9 ) month="Sep" ;; 10) month="Oct" ;;
11) month="Nov" ;; 12) month="Dec" ;;
* ) echo "$0: Unknown numeric month value $1" >&2; exit 1
esac
return 0
}
## Begin main script
if [ $# -ne 3 ] ; then
echo "Usage: $0 month day year" >&2
echo "Typical input formats are August 3 1962 and 8 3 2002" >&2
exit 1
fi
if [ $3 -lt 99 ] ; then
echo "$0: expected four-digit year value." >&2; exit 1
fi
if [ -z $(echo $1|sed 's/[[:digit:]]//g') ]; then
monthnoToName $1
else
# Normalize to first three letters, first upper, rest lowercase
month="$(echo $1|cut -c1|tr '[:lower:]' '[:upper:]')"
month="$month$(echo $1|cut -c2-3 | tr '[:upper:]' '[:lower:]')"
fi
echo $month $2 $3
exit 0
腳本分析:
1) 定義了函數(shù)monthnoToName(),用來轉(zhuǎn)換用戶輸入的數(shù)字月份
2)首先判斷參數(shù)的個數(shù)是否為3個,其次判斷年份,接著是轉(zhuǎn)換月份格式。
3)if [ -z $(echo $1|sed 's/[[:digit:]]//g') ]; 這句話有點意思,是如果$1被執(zhí)行sed替換的話,即$1中存在數(shù)字
則執(zhí)行函數(shù)monthnoToName(),來轉(zhuǎn)換數(shù)字月份。
4)month="$(echo $1|cut -c1|tr '[:lower:]' '[:upper:]')"
month="$month$(echo $1|cut -c2-3 | tr '[:upper:]' '[:lower:]')"
將輸入的字符月份轉(zhuǎn)換為標(biāo)準(zhǔn)格式。
5)這個腳本最大的缺陷是雖然將日期的格式轉(zhuǎn)換了,但不能檢測過濾不存在的日期。

