2017-02-20 126 views
1

我得到文本文件中的日期並將其分配給一個變量。當我用grep從文件之日起,我得到這個,將系統日期與文本文件中的日期進行比較

Not After : Jul 28 14:09:57 2017 GMT 

所以我只能修剪出日期,使用此命令

echo $dateFile | cut -d ':' -f 2,4 

其結果將是

Jul 28 14:57 2017 GMT 

如何我是否將此日期轉換爲秒數,以便我可以將其與系統日期進行比較?如果超過2天。

我有這段代碼,但它不起作用。我在運行時遇到錯誤消息。我認爲它是因爲$ dateFile是一個文本文件,它不知道如何轉換它。任何幫助,將不勝感激。

#!/bin/bash 

$dateFile=grep "After :" myfile.txt | cut -d ':' -f 2,4 

AGE_OF_MONTH="172800" # 172800 seconds = 2 Days 
NOW=$(date +%s) 
NEW_DATE=$((NOW - AGE_OF_MONTH)) 

if [ $(stat -c %Y "$dateFile") -lt ${NEW_DATE} ]; then 
    echo Date Less then 2 days 
else 
    echo Date Greater then 2 days 
fi 

回答

0

您的腳本中有幾個錯誤。請嘗試以下:

#!/bin/bash 

# capture the seconds since epoch minus 2 days 
NOW=`expr $(date '+%s') - 172800` 

# read every line in the file myfile.txt 
while read -r line; 
do 
    # remove the unwanted words and leave only the date info 
    s=`echo $line | cut -d ':' -f 2,4` 
    # parse the string s into a date and capture the number of seconds since epoch 
    date=$(date -d "$s" '+%s') 

    # compare and print output 
    if [ $date -lt $NOW ]; then 
    echo "Date Less then 2 days, s=$s, date=$date, now=$NOW" 
    else 
    echo "Date Greater then 2 days, s=$s, date=$date, now=$NOW" 
    fi 
done < myfile.txt 

然而,這是行不通的: $dateFile=grep "After :" myfile.txt | cut -d ':' -f 2,4。在shell中,您不能在$前加一個變量名稱,因爲shell會嘗試將結果評估爲變量,並且爲了執行命令並將其分配給需要用$(....)或反引號括起來的變量。

例具有可變及輸送到while:

#!/bin/sh 

dateFile=`grep "After :" my.txt | cut -d ':' -f 2,4` 

# capture the seconds since epoch minus 2 days 
NOW=`expr $(date '+%s') - 172800` 

echo "$dateFile" | while read -r line; 
do 
    # parse the string s into a date and capture the number of seconds since epoch 
    date=$(date -d "$line" '+%s') 

    # compare and print output 
    if [ $date -lt $NOW ]; then 
    echo "Date Less then 2 days, s=$line, date=$date, now=$NOW" 
    else 
    echo "Date Greater then 2 days, s=$line, date=$date, now=$NOW" 
    fi 
done 

實例管道將grep和的同時:

#!/bin/sh 

# capture the seconds since epoch minus 2 days 
NOW=`expr $(date '+%s') - 172800` 

grep "After :" myFile.txt | cut -d ':' -f 2,4 | while read -r line; 
do 
    # parse the string s into a date and capture the number of seconds since epoch 
    date=$(date -d "$line" '+%s') 

    # compare and print output 
    if [ $date -lt $NOW ]; then 
    echo "Date Less then 2 days, s=$line, date=$date, now=$NOW" 
    else 
    echo "Date Greater then 2 days, s=$line, date=$date, now=$NOW" 
    fi 
done 

希望這闡明你的問題。

+0

您的代碼完美無缺。謝謝。只是想知道爲什麼你需要一個循環來讀取文件中的每一行,導致命令grep會自動獲取你需要的信息? – user1736786

+0

我編輯了我的答案,以迴應你的問題。如果您滿意,請選擇正確的答案。 – artemisian

相關問題