I'm trying to find a way to grep how many messages in a file are older than 14 days and have a value of number of results return

Example going with today's date of 20160616. $grep 'Put Date' filename:

Put Date     :'20160425'
Put Date     :'20160501'
Put Date     :'20160514'
Put Date     :'20160609'
Put Date     :'20160610'
Put Date     :'20160616'

The results should see the following are older than 14 days and would return 3 :

Put Date     :'20160226'
Put Date     :'20160501'
Put Date     :'20160514'
  • I removed the blank lines between each of the lines in your input. I assume you had only added them for clarity. If they are actually part of your file please replace them. – terdon Jun 16 '16 at 15:47

You could use:

awk -v threshold=$(date "--date=$(date) -14 day" +%Y%m%d) -F "'" '$2 < threshold' filename | wc -l

This is similar to the solution in this post except that the date is computed inline.

Note: filename should be replaced by the name of your file.

Also, remember to be careful with your rules for boundary dates (check the edge conditions).


An awk solution was posted, so I'll do a grep-based one.

First, create a file with dates that you don't want to see, one per line. This will only be 15 entries, so it's not much processing needed and is quick. The following requires GNU date, which on my [BSD] system is installed as gdate:

while (( i < 15 )); do
    gdate -d "now -$(( i++ )) days" +"%Y%m%d"
done >dates_to_skip

Once that's done, you can simply use that as the filter for fgrep -v:

fgrep -v -f dates_to_skip mydata

Not the answer you're looking for? Browse other questions tagged or ask your own question.