Script to delete old entries from a file

I need to remove the file entries that are 30 days old. I have a file with the below data.

111.XX.XX.99 - - [13/Oct/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [04/Nov/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [01/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [01/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [16/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [17/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [22/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [17/Jan/2013:23:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [17/Jan/2013:22:27:35 -0400] "GET /folder1/wp-content" 304

After applying the script to the file, the output should be as follows.

111.XX.XX.99 - - [17/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [22/Dec/2012:22:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [17/Jan/2013:23:27:35 -0400] "GET /folder1/wp-content" 304
111.XX.XX.99 - - [17/Jan/2013:22:27:35 -0400] "GET /folder1/wp-content" 304

The lines which is old more than 30 days should be removed from the output.

Why need a script? A "FIND" command is sufficient!

find <directory> -type f -mtime +30 -exec rm -f {} \;

You can build your command from the site BUILD FIND

I dont need to delete files that are old, but the contents inside a file that are 30 days old. We can check the date and delete lines that are date pattern older than 30 days.

is your file sorted according to date?

Please read my first post clearly. I have expalined it clearly :slight_smile:

A simple algorithm would be following.

Get the current date store it in a variable
While you read a file using Readdir,
open a file handle
start reading a file using that file handle (read by line)
Now keep copying the content of file into another bkp file until you reach the day which is 30 days older from today (refer my second line)
once that is done close FH, and unlink the file (delete it) and name the bkp file as originial one.
End of while loop.

Let me know how that works out - if you didn't get it send me sample file I'll write a small script demonstrating how to do that.