Example No. 2
做为shell编写人员,常常面对数据格式不一致的问题,将数据标准话后输出是一个须要解决问题,本示例以MySQL的时间为例,脚本输入月、日、年三个参数,将其标准化后输出,月份以英文标准输出,年份若是是4个数字,直接输出,若是是0~69,则年份为2000~2069,若是是70~99,则年份为1970~1999;
脚本示例:git
#!/bin/bash #shell name:shell_format.sh #author by woon #数据标准化输出示例 Month_to_name() { 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: 错误的月份格式:$1" >&2; exit 1 esac return 0 } #脚本主体 if [ $# -ne 3 ]; then echo "Usage: $0 month day year\nThe correct formats are 8 21 2018 or August 21 2018" exit 1 fi #判断年份是不是数字,并拼接年份 #判断是不是个位数 if [ -z $(echo $3 | sed 's/^[0-9]//g') ];then year=200$3 #判断是不是10-69之间数字 elif [ -z $(echo $3 | sed 's/^[1-6][0-9]//g') ]; then year=20$3 elif [ -z $(echo $3 | sed s'/^[7-9][0-9]//g') ]; then year=19$3 elif [ -z $(echo $3 | sed 's/^[0-9]\{4\}//g') ]; then year=$3 else echo "The yeat's formats are wrong:$3" exit 2 fi #脚本主体 if [ -z $(echo $1 | sed 's/[[:digit:]]//g') ]; then Month_to_name $1 else month=$(${$1%${$1#?}}|tr '[a-z]' '[A-Z]')$(echo $1|cut -c2-3 | tr '[A-Z' '[a-z]') fi echo $month $2 $year exit 0
运行结果:shell