您的腳本中有幾個錯誤。請嘗試以下:
#!/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
希望這闡明你的問題。
您的代碼完美無缺。謝謝。只是想知道爲什麼你需要一個循環來讀取文件中的每一行,導致命令grep會自動獲取你需要的信息? – user1736786
我編輯了我的答案,以迴應你的問題。如果您滿意,請選擇正確的答案。 – artemisian