我用这个ksh函数将“2011年1月1日”格式转换为“1.1.2011”。将#!/ bin/ksh日期转换功能翻译成#!/ bin/sh
#!/bin/ksh
##---- function to convert 3 char month into numeric value ----------
convertDate()
{
echo $1 | awk -F"-" '{print $1,$2,$3}' | read day mm yyyy ## split the date arg
typeset -u mmm=`echo $mm` ## set month to uppercase
typeset -u months=`cal $yyyy | grep "[A-Z][a-z][a-z]"` ## uppercase list of all months
i=1 ## starting month
for mon in $months; do ## loop thru month list
## if months match, set numeric month (add zero if needed); else increment month counter
[[ "$mon" = "$mmm" ]] && typeset -xZ2 monthNum=$i || ((i += 1))
done ## end loop
echo $day.$monthNum.`echo $yyyy | cut -c3-` ## return all numeric date format ddmmyyyy
}
但我需要在#!/ bin/sh中使用这个函数。所以我试图重写它...
#!/bin/sh
##---- function to convert 3 char month into numeric value ----------
convertDate()
{
echo $1 | awk -F"-" '{print $1,$2,$3}' | read day mm yyyy ## split the date arg
echo $mm #IT SEEMS LIKE THE PROBLEM IS IN THE PREVIOUS LINE, BECAUSE THIS VARIABLE IS EMPTY IN #!/bin/sh, BUT IF YOU CHANGE IT TO #!/bin/ksh EVERYTHING SEEM TO BE FINE, THEN FUNCTION WORKS CORRECTLY.
mmm=`echo $mm | tr '[a-z]' '[A-Z]'`
months=`cal $yyyy | grep "[A-Z][a-z][a-z]" | tr '[a-z]' '[A-Z]'`
i=1 ## starting month
for mon in $months; do ## loop thru month list
## if months match, set numeric month (add zero if needed); else increment month counter
if [ "$mon" = "$mmm" ]; then
monthNum=`printf '%02d' $i`
else
i=`expr $i + 1`
fi
done ## end loop
echo $day.$monthNum.`echo $yyyy | cut -c3-` ## return all numeric date format ddmmyyyy
}
convertDate "20-May-2010"
但它不工作(读的最后一个脚本大写评论):(
帮助!
为什么你需要用它来/ bin/sh的运行?在Solaris 10及更早版本中,此外壳不是用于新脚本,而是仅用于保证与旧脚本的兼容性。编辑:对不起,我刚刚注意到你似乎使用Linux,而不是Solaris,所以此评论不适用。 – jlliagre 2011-06-05 21:16:10
不,我使用Solaris(实际上我们的客户使用它,而且我正在为他们编写这个脚本)。但我必须使用/ bin/sh(所以我的老板说,尽管我不同意)。无论如何,geekosour的帖子有所帮助。谢谢你的努力:) – Eedoh 2011-06-05 21:39:54
如果你的老板希望你使用sh而不是ksh,那么在Solaris上选择符合POSIX标准的bourne shell:'#!/ usr/xpg4/bin/sh' – jlliagre 2011-06-06 09:47:13