我在文本文件中获取日期并将其分配给变量。当我从文件中查找日期时,我明白了,
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 :(得分: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将尝试将结果作为变量进行评估,并且还要执行命令并将其分配给需要在{{1或者用反引号。
变量示例并将其管道输入:
$(....)
示例管道grep和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
希望这能澄清你的问题。