2017-02-20 7 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합니다. 쉘에서는 변수 이름 앞에 $이라는 접두사를 붙일 수 없습니다. 쉘은 결과를 변수로 평가하고 명령을 실행하여 변수에 할당하려면 $(....) 또는 백틱으로 둘러싸 야합니다. 변수와 반면에 배관와

예 : 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