我有一个按以下顺序排列多行的文件
Name=abc Date=12/10/2013
Name=xyz Date=11/01/2014
Name=pqr Date=06/30/2014
Name=klm Date=07/08/2014
等等。日期格式为mm / dd / yyyy。
我想编写一个shell脚本,它将遍历每一行,它应该返回我的Date
即将在未来一周内出现的行。就像在这里,如果我今天运行脚本,它必须返回我
Name=pqr Date=06/30/2014
如何实现?
答案 0 :(得分:2)
# Get today's date in natively sortable format: YYYYMMDD
today=$(date +%Y%m%d)
# Get next week's date in natively sortable format: YYYYMMDD
oneweek=$(date -d "+1 week" +%Y%m%d)
# Pass the start and end dates to awk as variables.
# Use `=` as the awk delimiter.
# Split the third field on `/` to convert the date to the natively sortable format.
# Compare converted date to start and end values (as an `awk` pattern so true results use the default `awk` print action).
awk -v start=$today -v end=$oneweek -F= '{split($3, a, /\//)} (a[3] a[1] a[2] > start) && (a[3] a[1] a[2] < end)' file
答案 1 :(得分:0)
简单的方法是从每一行获取日期并将其从大纪元时间转换为秒,并进行比较,如下所示。
读取行
DO
date_in_line=`echo $line | awk -F= '{print $NF}'`
date_after_1_week_in_sec=$(date -d "+1 week" +%s)
date_in_line_sec=$(date -d $date_in_line +%s)
if [ $date_in_line_sec -lt $date_after_1_week_in_sec ]; then
echo $line
fi
完成&lt; file.txt的
希望它有所帮助。