在 unix shell 中,如何将昨天的日期放入变量中?

发布于 2024-09-15 04:13:37 字数 232 浏览 9 评论 0原文

我有一个 shell 脚本,它执行以下操作以将当天的日期存储在变量“dt”中:

date "+%a %d/%m/%Y" | read dt
echo ${dt}

我如何将昨天日期放入变量中?

基本上我想要实现的是使用 grep 从日志文件中提取昨天的所有行,因为日志中的每一行都包含“Mon 01/02/2010”格式的日期。

多谢

I've got a shell script which does the following to store the current day's date in a variable 'dt':

date "+%a %d/%m/%Y" | read dt
echo ${dt}

How would i go about getting yesterdays date into a variable?

Basically what i'm trying to achieve is to use grep to pull all of yesterday's lines from a log file, since each line in the log contains the date in "Mon 01/02/2010" format.

Thanks a lot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

断舍离 2024-09-22 04:13:37
dt=$(date --date yesterday "+%a %d/%m/%Y")
echo $dt
dt=$(date --date yesterday "+%a %d/%m/%Y")
echo $dt
孤云独去闲 2024-09-22 04:13:37

在 Linux 上,您可以使用

date -d "-1 days" +"%a %d/%m/%Y"

On Linux, you can use

date -d "-1 days" +"%a %d/%m/%Y"
情痴 2024-09-22 04:13:37

您可以使用如下所示的 GNU date 命令

获取过去的日期

要获取昨天和过去的较早日期,请使用字符串 day ago:

date --date='yesterday'

date --date='1 day ago'

date --date='10 day ago'

date -- date='10 周前'

date --date='10 个月前'

date --date='10 年前'

获取未来的日期

要获取明天和后天(明天+N),请使用日期词获取未来的日期,如下所示:

date --date='tomorrow'

date --date='1 day'

date --date ='10天'

日期 --date='10周'

日期 --date='10个月'

日期 --date='10年'

You can use GNU date command as shown below

Getting Date In the Past

To get yesterday and earlier day in the past use string day ago:

date --date='yesterday'

date --date='1 day ago'

date --date='10 day ago'

date --date='10 week ago'

date --date='10 month ago'

date --date='10 year ago'

Getting Date In the Future

To get tomorrow and day after tomorrow (tomorrow+N) use day word to get date in the future as follows:

date --date='tomorrow'

date --date='1 day'

date --date='10 day'

date --date='10 week'

date --date='10 month'

date --date='10 year'

山色无中 2024-09-22 04:13:37

如果您有可用的 Perl(并且您的 date 没有像 yesterday 这样的好功能),您可以使用:

pax> date
Thu Aug 18 19:29:49 XYZ 2010

pax> dt=$(perl -e 'use POSIX;print strftime "%d/%m/%Y%",localtime time-86400;')

pax> echo $dt
17/08/2010

If you have Perl available (and your date doesn't have nice features like yesterday), you can use:

pax> date
Thu Aug 18 19:29:49 XYZ 2010

pax> dt=$(perl -e 'use POSIX;print strftime "%d/%m/%Y%",localtime time-86400;')

pax> echo $dt
17/08/2010
复古式 2024-09-22 04:13:37

如果您使用的是 Mac 或 BSD 或其他没有 --date 选项的设备,您可以使用:

date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y'

更新:或者也许...

date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y'

If you are on a Mac or BSD or something else without the --date option, you can use:

date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y'

Update: or perhaps...

date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y'
陪你搞怪i 2024-09-22 04:13:37

我在 Linux 中有 shell 脚本,以下代码对我有用:

#!/bin/bash
yesterday=`TZ=EST+24 date +%Y%m%d` # Yesterday is a variable
mkdir $yesterday # creates a directory with  YYYYMMDD format

I have shell script in Linux and following code worked for me:

#!/bin/bash
yesterday=`TZ=EST+24 date +%Y%m%d` # Yesterday is a variable
mkdir $yesterday # creates a directory with  YYYYMMDD format
眉目亦如画i 2024-09-22 04:13:37

尝试以下方法:

dt=`case "$OSTYPE" in darwin*) date -v-1d "+%s"; ;; *) date -d "1 days ago" "+%s"; esac`
echo $dt

它适用于 Linux 和 OSX。

Try the following method:

dt=`case "$OSTYPE" in darwin*) date -v-1d "+%s"; ;; *) date -d "1 days ago" "+%s"; esac`
echo $dt

It works on both Linux and OSX.

另类 2024-09-22 04:13:37

您至少有 2 个选择

  1. 使用 perl:

    perl -e '@T=本地时间(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[ 5]+1900)'
    
  2. 安装GNU date(如果我没记错的话,它在sh_utils包中)

    date --date 昨天 "+%a %d/%m/%Y" |读取数据
    回声 ${dt}
    
  3. 不确定这是否有效,但您也许可以使用负时区。如果您使用的时区比当前时区早 24 小时,则只需使用 date

You have atleast 2 options

  1. Use perl:

    perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)'
    
  2. Install GNU date (it's in the sh_utils package if I remember correctly)

    date --date yesterday "+%a %d/%m/%Y" | read dt
    echo ${dt}
    
  3. Not sure if this works, but you might be able to use a negative timezone. If you use a timezone that's 24 hours before your current timezone than you can simply use date.

对岸观火 2024-09-22 04:13:37

下面是一个 ksh 脚本,用于计算第一个参数的前一个日期,并在 Solaris 10 上进行了测试。

#!/bin/ksh
 sep=""
 today=$(date '+%Y%m%d')
 today=${1:-today}
 ty=`echo $today|cut -b1-4` # today year
 tm=`echo $today|cut -b5-6` # today month
 td=`echo $today|cut -b7-8` # today day
 yy=0 # yesterday year
 ym=0 # yesterday month
 yd=0 # yesterday day

 if [ td -gt 1 ];
 then
         # today is not first of month
         let yy=ty       # same year
         let ym=tm       # same month
         let yd=td-1     # previous day
 else
         # today is first of month
         if [ tm -gt 1 ];
         then
                 # today is not first of year
                 let yy=ty       # same year
                 let ym=tm-1     # previous month
                 if [ ym -eq 1 -o ym -eq 3 -o ym -eq 5 -o ym -eq 7 -o ym -eq 8 -o ym -     eq 10 -o ym -eq 12 ];
                 then
                         let yd=31
                 fi
                 if [ ym -eq 4 -o ym -eq 6 -o ym -eq 9 -o ym -eq 11 ];
                 then
                         let yd=30
                 fi
                 if [ ym -eq 2 ];
                 then
                         # shit... :)
                         if [ ty%4 -eq 0 ];
                         then
                                 if [ ty%100 -eq 0 ];
                                 then
                                         if [ ty%400 -eq 0 ];
                                         then
                                         #echo divisible by 4, by 100, by 400
                                                 leap=1 
                                         else
                                         #echo divisible by 4, by 100, not by 400
                                                 leap=0
                                         fi
                                 else
                                         #echo divisible by 4, not by 100
                                         leap=1 
                                 fi
                         else
                                 #echo not divisible by 4
                                 leap=0 # not divisible by four
                         fi
                         let yd=28+leap
                 fi
         else
                 # today is first of year
                 # yesterday was 31-12-yy
                 let yy=ty-1     # previous year
                 let ym=12
                 let yd=31
         fi
 fi
 printf "%4d${sep}%02d${sep}%02d\n" $yy $ym $yd

测试

bin$ for date in 20110902 20110901 20110812 20110801 20110301 20100301 20080301 21000301 20000301 20000101 ; do yesterday $date; done
20110901
20110831
20110811
20110731
20110228
20100228
20080229
21000228
20000229
19991231

Here is a ksh script to calculate the previous date of the first argument, tested on Solaris 10.

#!/bin/ksh
 sep=""
 today=$(date '+%Y%m%d')
 today=${1:-today}
 ty=`echo $today|cut -b1-4` # today year
 tm=`echo $today|cut -b5-6` # today month
 td=`echo $today|cut -b7-8` # today day
 yy=0 # yesterday year
 ym=0 # yesterday month
 yd=0 # yesterday day

 if [ td -gt 1 ];
 then
         # today is not first of month
         let yy=ty       # same year
         let ym=tm       # same month
         let yd=td-1     # previous day
 else
         # today is first of month
         if [ tm -gt 1 ];
         then
                 # today is not first of year
                 let yy=ty       # same year
                 let ym=tm-1     # previous month
                 if [ ym -eq 1 -o ym -eq 3 -o ym -eq 5 -o ym -eq 7 -o ym -eq 8 -o ym -     eq 10 -o ym -eq 12 ];
                 then
                         let yd=31
                 fi
                 if [ ym -eq 4 -o ym -eq 6 -o ym -eq 9 -o ym -eq 11 ];
                 then
                         let yd=30
                 fi
                 if [ ym -eq 2 ];
                 then
                         # shit... :)
                         if [ ty%4 -eq 0 ];
                         then
                                 if [ ty%100 -eq 0 ];
                                 then
                                         if [ ty%400 -eq 0 ];
                                         then
                                         #echo divisible by 4, by 100, by 400
                                                 leap=1 
                                         else
                                         #echo divisible by 4, by 100, not by 400
                                                 leap=0
                                         fi
                                 else
                                         #echo divisible by 4, not by 100
                                         leap=1 
                                 fi
                         else
                                 #echo not divisible by 4
                                 leap=0 # not divisible by four
                         fi
                         let yd=28+leap
                 fi
         else
                 # today is first of year
                 # yesterday was 31-12-yy
                 let yy=ty-1     # previous year
                 let ym=12
                 let yd=31
         fi
 fi
 printf "%4d${sep}%02d${sep}%02d\n" $yy $ym $yd

Tests

bin$ for date in 20110902 20110901 20110812 20110801 20110301 20100301 20080301 21000301 20000301 20000101 ; do yesterday $date; done
20110901
20110831
20110811
20110731
20110228
20100228
20080229
21000228
20000229
19991231
や莫失莫忘 2024-09-22 04:13:37

感谢大家的帮助,但由于我使用的是 HP-UX(毕竟:你付出的越多,你获得的功能就越少......)我不得不求助于 perl:

perl -e '@T=localtime(time-86400);printf("%02d/%02d/%04d",$T[3],$T[4]+1,$T[5]+1900)' | read dt

Thanks for the help everyone, but since i'm on HP-UX (after all: the more you pay, the less features you get...) i've had to resort to perl:

perl -e '@T=localtime(time-86400);printf("%02d/%02d/%04d",$T[3],$T[4]+1,$T[5]+1900)' | read dt
朮生 2024-09-22 04:13:37

如果您的 HP-UX 安装安装了 Tcl,您可能会发现它的日期算术非常可读(不幸的是 Tcl shell 没有像 perl 那样很好的“-e”选项):

dt=$(echo 'puts [clock format [clock scan yesterday] -format "%a %d/%m/%Y"]' | tclsh)
echo "yesterday was $dt"

这将处理所有夏令时麻烦。

If your HP-UX installation has Tcl installed, you might find it's date arithmetic very readable (unfortunately the Tcl shell does not have a nice "-e" option like perl):

dt=$(echo 'puts [clock format [clock scan yesterday] -format "%a %d/%m/%Y"]' | tclsh)
echo "yesterday was $dt"

This will handle all the daylight savings bother.

罗罗贝儿 2024-09-22 04:13:37

如果您没有支持 --yesterday 的 date 版本,并且您不想使用 perl,则可以使用我的这个方便的 ksh 脚本。默认情况下,它返回昨天的日期,但您可以向它提供一个数字,它会告诉您过去很多天的日期。如果你看向遥远的过去,它就会开始放慢一点。 100,000 天前是 1738 年 1 月 30 日,尽管我的系统花了 28 秒才算出来。

    #! /bin/ksh -p

    t=`date +%j`
    ago=$1
    ago=${ago:=1} # in days
    y=`date +%Y`

    function build_year {
            set -A j X $( for m in 01 02 03 04 05 06 07 08 09 10 11 12
                    {
                            cal $m $y | sed -e '1,2d' -e 's/^/ /' -e "s/ \([0-9]\)/ $m\/\1/g"
                    } )
            yeardays=$(( ${#j[*]} - 1 ))
    }

    build_year

    until [ $ago -lt $t ]
    do
            (( y=y-1 ))
            build_year
            (( ago = ago - t ))
            t=$yeardays
    done

    print ${j[$(( t - ago ))]}/$y

If you don't have a version of date that supports --yesterday and you don't want to use perl, you can use this handy ksh script of mine. By default, it returns yesterday's date, but you can feed it a number and it tells you the date that many days in the past. It starts to slow down a bit if you're looking far in the past. 100,000 days ago it was 1/30/1738, though my system took 28 seconds to figure that out.

    #! /bin/ksh -p

    t=`date +%j`
    ago=$1
    ago=${ago:=1} # in days
    y=`date +%Y`

    function build_year {
            set -A j X $( for m in 01 02 03 04 05 06 07 08 09 10 11 12
                    {
                            cal $m $y | sed -e '1,2d' -e 's/^/ /' -e "s/ \([0-9]\)/ $m\/\1/g"
                    } )
            yeardays=$(( ${#j[*]} - 1 ))
    }

    build_year

    until [ $ago -lt $t ]
    do
            (( y=y-1 ))
            build_year
            (( ago = ago - t ))
            t=$yeardays
    done

    print ${j[$(( t - ago ))]}/$y
十秒萌定你 2024-09-22 04:13:37

ksh93:

dt=${ printf "%(%a %d/%m/%Y)T" yesterday; }

或:

dt=$(printf "%(%a %d/%m/%Y)T" yesterday)

第一个在同一进程中运行,第二个在子 shell 中运行。

ksh93:

dt=${ printf "%(%a %d/%m/%Y)T" yesterday; }

or:

dt=$(printf "%(%a %d/%m/%Y)T" yesterday)

The first one runs in the same process, the second one in a subshell.

绮筵 2024-09-22 04:13:37

对于 Hp-UX,仅以下命令对我有用:

TZ=aaa24 date +%Y%m%d

您可以将其用作:

ydate=`TZ=aaa24 date +%Y%m%d`

echo $ydate

For Hp-UX only below command worked for me:

TZ=aaa24 date +%Y%m%d

you can use it as :

ydate=`TZ=aaa24 date +%Y%m%d`

echo $ydate

冷月断魂刀 2024-09-22 04:13:37

如果您有权访问 python,这是一个帮助程序,它将获取任意 n 天前的 yyyy-mm-dd 日期值:

function get_n_days_ago {
  local days=$1
  python -c "import datetime; print (datetime.date.today() - datetime.timedelta(${days})).isoformat()"
}

# today is 2014-08-24

$ get_n_days_ago 1
2014-08-23

$ get_n_days_ago 2
2014-08-22

If you have access to python, this is a helper that will get the yyyy-mm-dd date value for any arbitrary n days ago:

function get_n_days_ago {
  local days=$1
  python -c "import datetime; print (datetime.date.today() - datetime.timedelta(${days})).isoformat()"
}

# today is 2014-08-24

$ get_n_days_ago 1
2014-08-23

$ get_n_days_ago 2
2014-08-22
电影里的梦 2024-09-22 04:13:37
$var=$TZ;
TZ=$TZ+24;
date;
TZ=$var;

昨天会让您在 AIX 中并将 TZ 变量设置回原始值

$var=$TZ;
TZ=$TZ+24;
date;
TZ=$var;

Will get you yesterday in AIX and set back the TZ variable back to original

永言不败 2024-09-22 04:13:37

尽管所有答案都很好,但不幸的是它们都不适合我。所以我不得不写一些老派的东西。 (我使用的是最低限度的 Linux 操作系统)

$ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) )

您可以将其与日期的常用格式结合起来。例如。

$ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) ) +%Y-%m-%d

解释 :
以 epoc 秒( -d 选项)为单位输入日期,从中减去一天的等效秒数。这将给出精确的一天前的日期。

Though all good answers, unfortunately none of them worked for me. So I had to write something old school. ( I was on a bare minimal Linux OS )

$ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) )

You can combine this with date's usual formatting. Eg.

$ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) ) +%Y-%m-%d

Explanation :
Take date input in terms of epoc seconds ( the -d option ), from which you would have subtracted one day equivalent seconds. This will give the date precisely one day back.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文