YYYYMMDDHH在Unix中的shell脚本中进行日期操作 [英] YYYYMMDDHH date manipulation in shell script in Unix
问题描述
我的日期格式为YYYYMMDDHH,我想从中添加或减少小时数。 GNU date(date -d选项)在Linux中起着一种魅力的作用,但不像Solaris那样在非GNU env中执行。有人可以帮助我如何做到这一点吗?
I have a date in format "YYYYMMDDHH" and I want to add or subtract hours from it. The GNU date (date -d option) works like a charm in Linux but cant do this in non-GNU env like Solaris. Can someone please help me in how I can do this?
推荐答案
你应该检查 gdate
尚未安装在您的Solaris版本下(可能位于 / usr / gnu / bin / date
, / usr / sfw / bin / [g] date
, / usr / local / bin / [g] date
, / usr / csw / bin / [g] date
或只是 / usr / bin / gdate
取决于版本)。如果没有,应该很容易找到一个包含GNU日期并安装的软件包。
You should check if gdate
is not already installed under your release of Solaris (might be in /usr/gnu/bin/date
, /usr/sfw/bin/[g]date
, /usr/local/bin/[g]date
, /usr/csw/bin/[g]date
or just /usr/bin/gdate
depending on the version). If not, it should be easy to find a package containing GNU date and install it.
无论如何,这里是一个shell函数,它应该只是在Solaris版本的Solaris这样做我相信你想要的:
Anyway, here is a shell function that should just work under a stock Solaris release and that do what I believe you want:
f()
{
echo $1 | perl -MTime::Local -nle '
use POSIX 'strftime';
$op='$2'*3600;
$sec=timelocal(0,0,$4,$3,$2-1,$1) if /(\d{4})(\d{2})(\d{2})(\d{2})/;
$sec=$sec+$op;
print strftime "%Y%m%d%H\n", localtime($sec);'
}
$ f 2014010112 -24
2013123112
这篇关于YYYYMMDDHH在Unix中的shell脚本中进行日期操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!