Results 1 to 6 of 6
I have log files that should be parsed and then deleted by a script on a regular basis. Sometimes things don't work for a variety of reasons and the log ...
- 11-29-2010 #1Just Joined!
- Join Date
- Jul 2010
- Posts
- 15
Find files older than X and Count them.
I have log files that should be parsed and then deleted by a script on a regular basis. Sometimes things don't work for a variety of reasons and the log files sit and sit and are never dealt with.
What I need is a small script that can give me the files older than X days and a count of those files.
What I have so far helps me take care of things manually but I need a little automation in my life
Here is what I have:
I can count all the files in the necessary directories recursively with this: ls -laR | wc -l
And I can find all the files that are older than 10 days that haven't been deleted yet by doing this: find /home/mike/logs -type f -mtime +10
But how do I put both of them into a script that will just give me the end number of both?
Can someone help me out here?
- 11-30-2010 #2Just Joined!
- Join Date
- Jul 2008
- Posts
- 81
If you want file names and a count of them, use find(1) to get the names and gawk(1) to print and count.
$ find /home/mike/logs -type f -mtime +10 -print | gawk '{print $0}END{print NR}'
If you want more information per file, you can use the "-ls" operator of find(1).
$ find /home/mike/logs -type f -mtime +10 -ls | gawk '{print $0}END{print NR}'
This will give you even more information than "ls -l".
- 11-30-2010 #3Just Joined!
- Join Date
- Jul 2010
- Posts
- 15
Ok, that was a big help! Now I have it working.
How could I put that in a tiny .sh script that would echo the result?
So the script would run and give me the result?
- 11-30-2010 #4Linux Engineer
- Join Date
- Feb 2005
- Posts
- 1,044
Simplest way to count things is to use the program that's designed to do just that - wc
And to print the result:Code:find /home/mike/logs -type f -mtime +10 -print | wc -l
Do them as separate arguments to get echo to lose the leading spaces that wc puts on its counts.Code:echo "Number of files: " $(find /home/mike/logs -type f -mtime +10 -print | wc -l)
- 11-30-2010 #5Just Joined!
- Join Date
- Jul 2008
- Posts
- 81
That's where the original poster started. But I believe he wanted file names and other information as well as the count.
- 11-30-2010 #6Just Joined!
- Join Date
- Jul 2008
- Posts
- 81
Script:
Save as findscript.sh, put in a place that is in your $PATH. Ask if you don't understand $PATH.Code:# /bin/sh find $1 -type f -mtime +10 -print \ | gawk '{print $0}END{print NR}'
Run as:Code:$ chmod +x findscript.sh
If you want a bit of decoration on the results, change the gawk statement to:Code:$ findscript.sh /home/mike/logs
Code:gawk '{print $0}END{print "Number of files = " NR}'


Reply With Quote
