對于用戶輸入日期的合法性檢驗(yàn),是個(gè)很重要的問題,這個(gè)例子是簡單得取得用戶輸入的日期,并轉(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ù)的個(gè)數(shù)是否為3個(gè),其次判斷年份,接著是轉(zhuǎn)換月份格式。
3)if [ -z $(echo $1|sed 's/[[:digit:]]//g') ]; 這句話有點(diǎn)意思,是如果$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)這個(gè)腳本最大的缺陷是雖然將日期的格式轉(zhuǎn)換了,但不能檢測過濾不存在的日期。
標(biāo)簽:武漢 自貢 鎮(zhèn)江 丹東 滁州 優(yōu)質(zhì)小號(hào) 六盤水 百色
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《linux shell實(shí)現(xiàn)轉(zhuǎn)換輸入日期的格式》,本文關(guān)鍵詞 linux,shell,實(shí)現(xiàn),轉(zhuǎn)換,輸入,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。