-1

I need to find the entries from a huge log file which are 1 month older than the current date using shell scripts. The log entry date is in the 3rd field of each line. This is my sample log file:

0114374510,OK,10/23/2017 9:22:50 AM,0016692200,OK
0112364510,OK,10/23/2017 9:22:50 AM,0016692200,OK
0112364510,TX,10/21/2017 9:10:00 AM,0016692200,OK
0115364510,TX,10/21/2017 10:52:00 AM,0016692200,OK
0112368979,OK,7/29/2016 10:25:00 AM,0000718374,OK
0113368979,OK,7/29/2016 12:50:00 PM,0000718374,OK
0112368979,TX,9/16/2015 10:57:00 AM,0033545820,OK

Thanks!

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56

1 Answers1

0

Here is a solution, using grep to match certain lines in your file and date to manipulate dates.

Linux version

grep -E "$(date --date='-1 month' '+%m')/[0-9]+/$(date --date='-1 month' +'%Y') <your_file>"
  • date --date='-1 month' '+%m' - Subtract 1 month to the current date and print the month
  • [0-9]+ - Regex matching any number (any day in our case)
  • $(date --date='-1 month' +'%Y') - Subtract 1 month to the current date and print the year

macOS version

grep -E "$(date -v -1m '+%m')/[0-9]+/$(date -v -1m +'%Y') <your_file>"
  • date -v -1m '+%m' - Subtract 1 month to the current date and print the month
  • [0-9]+ - Regex matching any number (any day in our case)
  • date -v -1m +'%Y' - Subtract 1 month to the current date and print the year
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56