스크립트에 몇 가지 오류가 있습니다. 아래 시도하십시오 :
#!/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
희망.
코드가 완벽하게 작동합니다. 고맙습니다. 그냥 파일에있는 모든 줄을 읽는 루프가 필요한 이유는 grep 명령이 자동으로 필요한 정보를 얻게하기 때문입니다. ??? – user1736786
질문에 대답하기 위해 내 대답을 편집했습니다. 만족 스럽다면 정답으로 선택하십시오. – artemisian