2015-12-30 73 views
-1

我需要一些幫助,從每隔4行減去來自下一個日期的每第3行的每個日期。請參閱下面的文件部分..外殼腳本來分開日期

Name: John 
Category: Subscriber 
4/6/14 8:00 PM 
4/6/17 7:59 PM 
Name: Hari 
Category: Owner 
4/22/13 6:29 AM 
6/21/32 6:29 AM 
Name: Bob 
Category: Subscriber 
9/9/14 8:00 PM 
9/9/17 7:59 PM 

生成的文件應該是:

Name: John 
Category: Subscriber 
4/6/14 8:00 PM 
4/6/17 7:59 PM 
valid for 1095 days 
Name: Hari 
Category: Owner 
4/22/13 6:29 AM 
6/21/32 6:29 AM 
valid for 7361 days 
Name: Bob 
Category: Subscriber 
9/9/14 8:00 PM 
9/9/17 7:59 PM 
valid for 1095 days 
+1

顯示你嘗試過,或者你有什麼想法 –

回答

1

您可以使用for循環使用date -d做日期計算:

#!/bin/bash 

i=0 
while read -r; do 
    ((++i)) 
    echo "$REPLY" 
    (((i+1) % 4 == 0)) && d="$REPLY" 
    ((i % 4 == 0)) && printf "valid for %d days\n" \ 
      $((($(date -d "$REPLY" '+%s') - $(date -d "$d" '+%s'))/86400)) 
done < file 

輸出:

Name: John 
Category: Subscriber 
4/6/14 8:00 PM 
4/6/17 7:59 PM 
valid for 1095 days 
Name: Hari 
Category: Owner 
4/22/13 6:29 AM 
6/21/32 6:29 AM 
valid for 7000 days 
Name: Bob 
Category: Subscriber 
9/9/14 8:00 PM 
9/9/17 7:59 PM 
valid for 1095 days 
0

用Perl:

perl -MTime::Piece -MTime::Seconds -lpe ' 
    sub diff_time { 
     print "valid for ", int(($d2->epoch - $d1->epoch)/ONE_DAY), " days"; 
    } 
    s/^\s+|\s+$//g; # trim whitespace 
    $d1 = Time::Piece->strptime($_, "%m/%d/%y %I:%M %p") if $. % 4 == 3; 
    $d2 = Time::Piece->strptime($_, "%m/%d/%y %I:%M %p") if $. % 4 == 0; 
    diff_time if $. % 4 == 1 and $. > 1; 
    END {diff_time} 
' file