2017-02-20 12 views
1

テキストファイル内の日付を取得し、変数に割り当てます。私は、ファイルから日付をgrepするとき、私はこれを取得、システム日付と日付とをテキストファイルと比較する

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

だから私は、唯一の結果は

Jul 28 14:57 2017 GMT 

どうだろう

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

このコマンドを使用して、日付をトリミングこの日付を秒数に変換するので、システム日付と比較できますか? 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を。シェルでは変数名の前に接頭辞として$を付けることはできません。シェルは結果を変数として評価し、コマンドを実行してそれを変数に代入するために、$(....)またはバッククォートで囲む必要があります。変数としばらくに配管して

例:grepのと同時に配管

#!/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 

例:これは、あなたの質問に明確に

#!/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

関連する問題