Reputation: 75
I have a file having multiple lines in the following order
Name=abc Date=12/10/2013
Name=xyz Date=11/01/2014
Name=pqr Date=06/30/2014
Name=klm Date=07/08/2014
And so on. Date format is mm/dd/yyyy.
I want to write a shell script, which will traverse each line and it should return me the line, whose Date
is about to come in next 1 week. Like here, if I run the script today, it must return me
Name=pqr Date=06/30/2014
How to achieve that ?
Upvotes: 0
Views: 2640
Reputation: 1
Simple way is get date from each line and convert it to seconds from Epoch time and compare as shown below.
while read line
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
done < file.txt
Hope it helps.
Upvotes: 0
Reputation: 81052
# 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
Upvotes: 2