2014-01-21 151 views
1

我是Shell腳本的新手。Shell腳本在Linux中獲取日期

我想編寫一個腳本來獲取從格式YYYY用戶的任何隨機日期:MM:週二和前一週的週五的DD和回聲(顯示)日期。

例如,如果我給輸入日期爲2013-12-11
輸出應該

date1= 2013-12-06 
date2= 2013-12-10 

輸入日期作爲2013-12-07

輸出

date1= 2013-12-03 
date2= 2013-12-06 
+0

您的預期輸入/輸出似乎不一致。你對_週期的定義是什麼,即什麼時候根據你開始一個星期? – devnull

+1

可能的重複[如何讓bash日期腳本返回相對於非當前時間的星期幾?](http://stackoverflow.com/questions/9203747/how-do-i-get- (bash-date-script-to-return-a-day-of-the-week-relative-to-a-non)) – fedorqui

+0

上週的星期二和星期五或最近的星期二和星期五? – Alfe

回答

1

嘗試以下方法:

input=2013-12-11 
lastTues=$(date -d "$input -$(date -d "$input +5 days" +%u) days" +%Y-%m-%d) 
lastFri=$(date -d "$input -$(date -d "$input +2 days" +%u) days" +%Y-%m-%d) 

該命令首先計算輸入日期和上個星期二(或星期五)之間有多少天,請致電X。然後運行date -d "inputDate -X days"來計算新的日期。

1

Perl來救援:

#!/usr/bin/perl 
use warnings; 
use strict; 

use DateTime; 

sub tuefri { 
    my ($year, $month, $day) = split /[^0-9]/, shift; 
    my $date = 'DateTime'->new(year => $year, 
           month => $month, 
           day => $day, 
          ); 
    $date->subtract(days => 7); 
    my @result; 
    until (2 == @result) { 
     push @result, $date->ymd if grep $_ == $date->day_of_week, 2, 5; 
     $date->add(days => 1); 
    } 
    return @result 
} 

my $i = 1; 
print 'date', $i++, "= $_\n" for tuefri(shift); 
0

溶液使用python-dateutil模塊:

import fileinput 
from dateutil.relativedelta import TU, FR, relativedelta 
from datetime import date 

for line in fileinput.input(): 
    d = date(*(map(int, line.rstrip().split('-')))) 
    print(d + relativedelta(weekday=FR(-1))) 
    print(d + relativedelta(weekday=TU(-1))) 

運行它喜歡:

python script.py <<<"2013-12-11" 

即產率:

2013-12-06 
2013-12-10