23,125
社区成员
发帖
与我相关
我的任务
分享
#!/bin/sh
format_date () {
# check argument
[ -z $1 ] && echo "usage: format_date <date-string>" && return
line="$@"
# format line
line=$(echo $line | sed 's/[^0-9]\+/ /g')
line=$(echo $line | sed 's/ \([0-9]\) / 0\1 /g')
line=$(echo $line | sed 's/^\([0-9]\) /0\1 /g')
line=$(echo $line | sed 's/ \([0-9]\)$/ 0\1/g')
line=$(echo $line | sed 's/ \+//g')
length=$(echo -n $line | wc -c)
if [ $length -eq 8 ] ; then
# format YYYY-MM-DD 00:00:00
year=$(echo $line | cut -c 1-4)
month=$(echo $line | cut -c 5-6)
day=$(echo $line | cut -c 7-8)
echo "$year-$month-$day 00:00:00"
elif [ $length -eq 14 ] ; then
# format YYYY-MM-DD HH:MM:SS
year=$(echo $line | cut -c 1-4)
month=$(echo $line | cut -c 5-6)
day=$(echo $line | cut -c 7-8)
hour=$(echo $line | cut -c 9-10)
min=$(echo $line | cut -c 11-12)
second=$(echo $line | cut -c 13-14)
echo "$year-$month-$day $hour:$min:$second"
else
echo "Invalid date string: $@"
fi
}
format_date 2008/2/25
format_date 2008/2/25 22:33:44
format_date 2008/2/25 22:3:4
format_date 20080225
format_date 20080225223344