Convert date String to number on Solaris shell scr

2019-09-06 01:17发布

I have a date in the format "Thu Sep 22 3:50 2016", and I want to convert it to format: "2016-09-22"

I tried the following shell script, which works fine for 'date', but gives error for user specified string: (I am working on Solaris platform). Any inputs will be helpful.

Input:

 #!/usr/bin/sh  
mydate="Thu Sep 22  3:50 2016"  
echo `date  +"%Y-%m-%d"`  
echo `$mydate  +"%Y-%m-%d"`

Output

./testShell.sh  
**2016-09-22**  

./testShell.sh[6]: Thu: not found **[No such file or directory]**

Any pointers please?

标签: shell solaris
2条回答
Ridiculous、
2楼-- · 2019-09-06 01:40

Under Solaris 11, many GNU utilities are available under the /usr/gnu/bin directory so you just need to slightly modify your script to either use the full path the the GNU variant :

#!/bin/sh  
mydate="Thu Sep 22 3:50 2016"  
date  +"%Y-%m-%d"
/usr/gnu/bin/date -d "$mydate"  +"%Y-%m-%d"

or use the already existing symlink prefixed by g (for GNU):

gdate -d "$mydate"  +"%Y-%m-%d"

or set your PATH to look at /usr/gnu/bin first and keep your script unchanged.

PATH=/usr/gnu/bin:$PATH
查看更多
我命由我不由天
3楼-- · 2019-09-06 01:47

You can try something like this;

#!/bin/bash
mydate="Thu Sep 22  3:50 2016"  
date  +"%Y-%m-%d"
date -d "$mydate"  "+%Y-%m-%d"
查看更多
登录 后发表回答