0

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 ?

1
  • 1
    What have you tried so far? One hint I can give is that using the date command you can output a time using relative offsets like date --date="+1 week". Commented Jun 24, 2014 at 19:33

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

4 Comments

I tried to print the oneweek oneweek=$(date -d "+1 week" +%Y%m%d)...... it showed me a warning date: illegal option -- d...... :(
date is not a shell built-in (unless ksh has one for it) so the shell doesn't matter, but the version of the date utility does. I was using GNU coreutils date. It would seem the AIX date does not have that flag. Perhaps it has the long --date option instead?
I tried --date option also, but it didn't work..... I was not able to see the version of date also in my AIX by date --version...... Though all working good in Linux machine
@user3772505 What version of awk are you using?
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.