2011-06-05 67 views
0

我用这个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" 

但它不工作(读的最后一个脚本大写评论):(

帮助!

+0

为什么你需要用它来/ bin/sh的运行?在Solaris 10及更早版本中,此外壳不是用于新脚本,而是仅用于保证与旧脚本的兼容性。编辑:对不起,我刚刚注意到你似乎使用Linux,而不是Solaris,所以此评论不适用。 – jlliagre 2011-06-05 21:16:10

+0

不,我使用Solaris(实际上我们的客户使用它,而且我正在为他们编写这个脚本)。但我必须使用/ bin/sh(所以我的老板说,尽管我不同意)。无论如何,geekosour的帖子有所帮助。谢谢你的努力:) – Eedoh 2011-06-05 21:39:54

+1

如果你的老板希望你使用sh而不是ksh,那么在Solaris上选择符合POSIX标准的bourne shell:'#!/ usr/xpg4/bin/sh' – jlliagre 2011-06-06 09:47:13

回答

2

的问题是,是否read命令在子shell中运行,由于管线取决于到底是哪壳/bin/sh是,你会得到一个bash行为和另一名来自传统的UNIX(如Solaris)上/bin/sh使用set代替

虽然我可能会写

oIFS="$IFS" 
IFS=- 
set -- $1 
IFS="$oIFS" 
+0

很棒! for(int i = 0; i <1000000; i ++){cout <<“Thank You!\ n”; }我知道这个“谢谢”是C++,而不是shell,但我认为它是doo:D – Eedoh 2011-06-05 19:45:42