在unix shell中,如何将昨天的日期转换为变量?

时间:2022-12-22 23:49:32

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

我有一个shell脚本,它可以将当前日期存储在一个变量'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.

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

Thanks a lot

非常感谢

17 个解决方案

#1


11  

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

如果您有Perl可用(并且您的日期没有像昨天那样的好特性),您可以使用:

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

#2


56  

dt=$(date --date yesterday "+%a %d/%m/%Y")
echo $dt

#3


39  

On Linux, you can use

在Linux上,您可以使用。

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

#4


8  

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

如果您在Mac或BSD或其他没有日期选项的情况下,您可以使用:

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

Update: or perhaps...

更新:也许……

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

#5


8  

You can use GNU date command as shown below

可以使用GNU date命令,如下所示。

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'

日期,日期= ' 1天前'

date --date='10 day ago'

日期,日期= 10天前的

date --date='10 week ago'

日期,日期= ' 10周前'

date --date='10 month ago'

日期,日期= ' 10月前

date --date='10 year ago'

日期,日期= ' 10年前'

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:

明天和后天(明天+N)用日词来确定未来的日期:

date --date='tomorrow'

日期,日期= '明天'

date --date='1 day'

日期,日期= ' 1天'

date --date='10 day'

日期,日期=“十天”

date --date='10 week'

日期,日期= ' 10周

date --date='10 month'

日期,日期= ' 10个月'

date --date='10 year'

日期,日期=“十年”

#6


4  

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

我在Linux中有shell脚本,下面的代码为我工作:

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

#7


3  

You have atleast 2 options

你至少有两种选择。

  1. Use perl:

    使用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)

    安装GNU日期(如果我没记错的话,它在sh_utils包中)

    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.

    不确定是否可行,但是你可以使用一个负时区。如果你使用的时区比你现在的时区要早24小时,那么你可以简单地使用日期。

#8


2  

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

这里是一个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

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

#9


2  

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.

它在Linux和OSX上都有作用。

#10


1  

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:

感谢所有人的帮助,但由于我是HP-UX(毕竟:你付得越多,你得到的功能就越少…)我不得不求助于perl:

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

#11


1  

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):

如果您的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"

This will handle all the daylight savings bother.

这将解决所有的日光节约问题。

#12


1  

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.

如果您没有支持的日期版本——昨天您不想使用perl,那么您可以使用我的这个方便的ksh脚本。默认情况下,它会返回昨天的日期,但是你可以给它一个数字,它会告诉你过去许多天的日期。如果你放眼过去,它会开始减速。10万天前是1/30/1738,虽然我的系统花了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

#13


1  

ksh93:

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.

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

#14


1  

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:

如果您有访问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

#15


1  

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

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

昨天你会在AIX上找到你,把TZ变量设置回原来的位置吗?

#16


0  

For Hp-UX only below command worked for me:

对于Hp-UX,以下命令为我工作:

TZ=aaa24 date +%Y%m%d

TZ = + % Y % m % d aaa24日期

you can use it as :

你可以把它当作:

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

ydate = ' TZ Y = aaa24日期+ % % m % d '

echo $ydate

echo $ ydate

#17


0  

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 )

虽然所有的答案都很好,但不幸的是没有一个对我有用。所以我不得不写一些旧的东西。(我在一个简单的Linux操作系统上)

$ 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.

说明:以epoc秒(-d选项)的形式进行日期输入,您可以从中减去一天的等效秒数。这将在一天之内精确地给出日期。

#1


11  

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

如果您有Perl可用(并且您的日期没有像昨天那样的好特性),您可以使用:

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

#2


56  

dt=$(date --date yesterday "+%a %d/%m/%Y")
echo $dt

#3


39  

On Linux, you can use

在Linux上,您可以使用。

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

#4


8  

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

如果您在Mac或BSD或其他没有日期选项的情况下,您可以使用:

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

Update: or perhaps...

更新:也许……

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

#5


8  

You can use GNU date command as shown below

可以使用GNU date命令,如下所示。

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'

日期,日期= ' 1天前'

date --date='10 day ago'

日期,日期= 10天前的

date --date='10 week ago'

日期,日期= ' 10周前'

date --date='10 month ago'

日期,日期= ' 10月前

date --date='10 year ago'

日期,日期= ' 10年前'

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:

明天和后天(明天+N)用日词来确定未来的日期:

date --date='tomorrow'

日期,日期= '明天'

date --date='1 day'

日期,日期= ' 1天'

date --date='10 day'

日期,日期=“十天”

date --date='10 week'

日期,日期= ' 10周

date --date='10 month'

日期,日期= ' 10个月'

date --date='10 year'

日期,日期=“十年”

#6


4  

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

我在Linux中有shell脚本,下面的代码为我工作:

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

#7


3  

You have atleast 2 options

你至少有两种选择。

  1. Use perl:

    使用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)

    安装GNU日期(如果我没记错的话,它在sh_utils包中)

    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.

    不确定是否可行,但是你可以使用一个负时区。如果你使用的时区比你现在的时区要早24小时,那么你可以简单地使用日期。

#8


2  

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

这里是一个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

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

#9


2  

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.

它在Linux和OSX上都有作用。

#10


1  

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:

感谢所有人的帮助,但由于我是HP-UX(毕竟:你付得越多,你得到的功能就越少…)我不得不求助于perl:

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

#11


1  

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):

如果您的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"

This will handle all the daylight savings bother.

这将解决所有的日光节约问题。

#12


1  

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.

如果您没有支持的日期版本——昨天您不想使用perl,那么您可以使用我的这个方便的ksh脚本。默认情况下,它会返回昨天的日期,但是你可以给它一个数字,它会告诉你过去许多天的日期。如果你放眼过去,它会开始减速。10万天前是1/30/1738,虽然我的系统花了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

#13


1  

ksh93:

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.

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

#14


1  

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:

如果您有访问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

#15


1  

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

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

昨天你会在AIX上找到你,把TZ变量设置回原来的位置吗?

#16


0  

For Hp-UX only below command worked for me:

对于Hp-UX,以下命令为我工作:

TZ=aaa24 date +%Y%m%d

TZ = + % Y % m % d aaa24日期

you can use it as :

你可以把它当作:

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

ydate = ' TZ Y = aaa24日期+ % % m % d '

echo $ydate

echo $ ydate

#17


0  

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 )

虽然所有的答案都很好,但不幸的是没有一个对我有用。所以我不得不写一些旧的东西。(我在一个简单的Linux操作系统上)

$ 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.

说明:以epoc秒(-d选项)的形式进行日期输入,您可以从中减去一天的等效秒数。这将在一天之内精确地给出日期。