2014-06-14 15 views
2

計算這種差異我有一個名爲Test1.dat文件及其內容的情況如下如何在UNIX

[email protected]:10:15 
[email protected]:15:23 
[email protected]:26:56 
[email protected]:46:56 
[email protected]:15:23 

請注意,@符號之後是HH:MM:SS格式如下。我現在的問題是我想計算當前時間與文件中當前時間之間的時間差,並僅提取時間差超過30分鐘的文件名。所以如果當前時間是11:00:00,我想獲取在30分鐘前到達的文件,所以基本上是前三個文件。

回答

2

awk應該做的:

awk [email protected] '$2>=from && $2<=to' from="$(date +%H:%M:%S -d -30min)" to="$(date +%H:%M:%S)" file 

如果你只需要得到最後的30分鐘(在你情況下,你需要的第一個,因爲你不喜歡11:30):

awk [email protected] '$2>=from' from="$(date +%H:%M:%S -d -30min)" file 
+0

嗨,我該如何打印這些行。? – user2647888

+0

@ user2647888由於'awk'只需測試零件,並且沒有動作部分,它就會執行默認動作:'{print $ 0}'(打印行)。所以這個'awk'應該做到這一切。 – Jotne

1

您還可以使用bash腳本並得到結果

#!/bin/bash 
current=`date '+%s'` 
needed_time=`echo "$current - 60 * 30" | bc` 
while read line ; do 
    time=`echo $line |sed -r 's/[^@]*.(.*)/\1/g'` 
    user_time=`date -d $time '+%s'` 
      if [ $user_time -le $needed_time ] ; then 
      echo "$line" 
    fi 
done < file_name  
1

可能是這個答案嗎?

awk [email protected] '{ts = systime(); thirty_mins = 30 * 60; thirty_mins_ago = ts - thirty_mins; if ($2 < strftime("%H:%M:%S", thirty_mins_ago)) print $2 }' <file.txt 

strftime是一個GAWK(gnu awk)擴展。

+0

'strftime'是'gnu awk'的擴展,所以你應該添加這個信息。 – Jotne

+0

當然,現在我看到更新我的信息與你的信息。 –