Reputation: 57
I have a file which contains a date at column 7, my requirement is to compare it with today's date and if it is less then it, than remove that complete line. Also if any date mentioned at column 7 is more then 15 days then modify it to maximum 15 days
example below-
now="$(date +'%d-%m-%Y')"
now=24-02-2021
file.txt
abc xyz pqr NFS 5 abc.vol
abc xyz pqr NFS 50 xyz.bal 23-02-2021
abc xyz pqr NFS 5 abcd.xyz
abc xyz pqr NFS 15 pqr.vol 25-02-2023
abc xyz pqr NFS 5 xyz.bal 24-03-2021
abc xyz pqr NFS 3 pqrst.vol 19-01-2019
output should be-
abc xyz pqr NFS 5 abc.vol
abc xyz pqr NFS 5 abcd.xyz
abc xyz pqr NFS 15 pqr.vol 11-03-2021
abc xyz pqr NFS 5 xyz.bal 24-03-2021
I tried through awk but it's fully not working
awk -v d=$now '$7 == "" && $7 < d' file.txt
Upvotes: 2
Views: 218
Reputation: 12877
Try the following GNU awk solution:
awk 'NF == 6 { print;next } { OFS="\t";split($7,map,"-");depoch=mktime(map[3]" "map[2]" "map[1]" 00 00 00");if (depoch<systime()) { next };if (+depoch>(systime()+1296000)) { $7=strftime("%d-%m-%Y",(systime()+1296000)) } }1' file.txt
Explanation:
awk 'NF == 6 { print; # If there is no date, print the line and skip to the next
next
}
{ OFS="\t"; # Set the output field delimiter to tab
split($7,map,"-"); # Split the date into the array map (getting day, month and year)
depoch=mktime(map[3]" "map[2]" "map[1]" 00 00 00"); # Create epoch format of the date
if (depoch<systime()) {
next # If epoch format of date is less than today, skip to the next record
};
if (depoch>(systime()+1296000)) {
$7=strftime("%d-%m-%Y",(systime()+1296000)) # If the date is greater than today +15 days, set the date to the date + 15 days (1296000 seconds) and format accordingly using strftime
}
}1' file.txt
I'm assuming that the required output posted is incorrect. 24-03-2021 is greater than 15 days from today and so should be changed to 11-03-2021
Upvotes: 1
Reputation: 133528
You are on right track, try changing your condition part in your code. Why its NOT working is you are asking awk
program to check if 7th field is NULL and meantime its value is lesser than variable which means performing same condition in other words so if a 7th field is NULL that will be for sure lesser than mentioned date. For getting results which are actually NOT NULL and having lesser date from current date, by your present condition you will only get those fields whose 7th field is NULL basically, so change it to OR condition to get lines if 7th field is empty OR lesser than today's date then print it simply.
now="$(date +'%d-%m-%Y')"
awk -v d=$now '$7 == "" || $7 < d' Input_file
Upvotes: 0