Find Oldest file in a directory tree


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Find Oldest file in a directory tree
# 15  
Old 02-01-2006
Well, yes. As Perderabo said, for a large number of files, the 'find | xargs' won't work - definitely not for your 47GB of files. Use mahendramahendr's perl script to do the job for you.
# 16  
Old 02-01-2006
Code:
#! /usr/bin/ksh

touch -t $(($(date "+%Y") + 1))$(date "+%m%d%H%M") notfound
OLDEST=notfound
find . -type f | while read f ; do
        [[ $f -ot $OLDEST ]] && OLDEST=$f
done
echo oldest file is $OLDEST
rm notfound
exit 0

# 17  
Old 06-20-2007
Hi,

I found the perl script helpful, thanks for posting it. However, I think there is one small bug in it.

Quote:
Originally Posted by mahendramahendr
my ($hr,$mn,$day,$mnth,$year)=(localtime((stat($str))[9]))[1,2,3,4,5];
I think it should be
($mn,$hr,$day,$mnth,$year)=...

$ perldoc -f localtime
localtime EXPR
localtime
Converts a time as returned by the time function to a 9-element
list with the time analyzed for the local time zone. Typically
used as follows:

# 0 1 2 3 4 5 6 7 8
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
[...]
# 18  
Old 09-22-2007
Bug Here is a one liner that will sort the oldest to the newest files...

in all the subdirectories...

find . -type f -printf "%T@ %p \n" | sort -n -k 1,1 | awk '{print $2}'

Tim
# 19  
Old 09-22-2007
More on deleting old files in subdirectories

Here is a perl script that I wrote for some commercial radio stations that want to delete the oldest archive file out of subdirectories from a root directory...

Code:
#!/usr/bin/perl

# This will sort all the files in various subdirectories by creation date.
# find . -type f -printf "%T@ %p \n" | sort -n -k 1,1 | awk '{print $2}'

$ls = "/usr/bin/find";
$df = "/bin/df -k";
$grep = "/bin/grep";
$lookfor = "*.mp3";
$dir = "/usr/local/public/archive/";
$percent = 95;

$fullfile = $dir . $lookfor;

open(LS_T, "$ls $dir -type f -printf '%T@ %p \n' | /usr/bin/sort -n -k 1,1 | /usr/bin/awk '{print \$2}'|") or die "Can't do $ls";
$i=0;
while(<LS_T>){
        chop;
        $filename = $_;
        $result=`$df $dir | $grep -v Filesystem`;
        chop $result;
        $_ = $result;
        tr/ / /s;
        ($fs,$kbytes,$used,$avail,$percentused,$mountedon) = split / /;
        chop $percentused;
        if ($percentused >= $percent){
                print "deleting \'$filename\'\n";
                `rm "$filename"`;
                $i++;
        } else {
                exit;
        }
}

# 20  
Old 09-23-2007
Ok... Found a bug soon as I posted this. In the previous example the "awk" will only print out the string after the number up to the end of the line or another space. Not good if you have files or directories with spaces. This would work better. Smilie

Code:
find . -type f -printf "%T@ %p \n" | sort -n -k 1,1 | sed 's/^[0-9]* //'

# 21  
Old 09-23-2007
Lightbulb GNU find $DIR -printf "%T@ %p\n" | sort -n | head -1

I would use the following command (assuming I had GNU find available):
find $DIR -printf "%T@ %p\n" | sort -n | head -1
The %T is modification time in a custom format; @ is the format specifier for for "seconds since the epoch. The rest should be pretty self-evident. %C would be used if you cared about the "ctime" (the time at which the file's inode was changed in any way, including modifications to the file contents (as with mtime) but also changes to ownership, permissions, link count? etc.

A couple of heuristics for scripting in general:

Any time you're trying to find files with specific characteristics other than matching a simple glob pattern and any of the simple test features like -d (directory) or -r (readable), etc, you almost always want to use the find command. Most of the switches and arguments to find control what find will consider returning (to things like -print, -exec, or -ls).

Any time you're going to compare or manipulate timestamps under UNIX you probably want to use "seconds since the epoch" (this allows simple numeric operations such as sorting or arithmetic adjustment).

So it seems obvious to just traverse the tree printing all the timestamps in a usable form; sort numerically and discard all but the first line. (You could also sort -nr, reversed, and take the last line with tail -1; but then your tail process has to read the entire pipe. In this example the head command can exit and break the pipe to kill to output from the sort command; which is marginally more efficient. Of course all of the expense in this is in the sort command ... it will take most of the CPU time and memory. Meanwhile, of course the find command will expend I/O -- that's inherent in traversing a filesystem tree).

P.S. If you need to convert a "seconds since the epoch" timestamp into a form you can read you can use an expression like:
date --date "$(( $(date +%s) - $TIMESTAMP )) seconds ago"
.. and naturally you can also specify any format you like for that output as you would with any other date


JimD (former Linux Gazette AnswerGuy)
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

Unable to find files, those can be present anywhere in the directory tree,based on its creation date

Hi I am unable to find files, those are present anywhere in the same directory tree, based on the creation date. I need to find the files with their path, as I need to create them in another location and move them. I need some help with a script that may do the job. Please help (2 Replies)
Discussion started by: sam192837465
2 Replies

2. UNIX for Dummies Questions & Answers

How to find directory listing from root to all files in tree format with details of perm/own/grp?

Hi, My apologies if my query is already available on this forum but I am new and could not find. I need a script to list all directories/sub directories and files with permissions/groups/owners. The script would run from home directory and should capture every directory. How do I do this? ... (4 Replies)
Discussion started by: 8709711
4 Replies

3. Shell Programming and Scripting

How to find files in directory tree by date

I'm using a directory naming convention to organize files as exemplified here: 2012/Aug/week-20-Aug/23-Thu/tuv.txt 2012/Aug/week-27-Aug/30-Thu/abc.txt 2012/Sep/week-27-Aug/01-Sat/def.txt 2012/Sep/week-03-Sep/07-Fri/xyz.txt How do I write a command that will list the file names abc.txt and... (4 Replies)
Discussion started by: siegfried
4 Replies

4. Shell Programming and Scripting

Deleting the oldest file in a directory

Hey! I have found similar posts both here and on other sites regarding this, but I cannot seem to get my script to work. I want to delete the oldest file in a test directory if there are more than two files. My script is currently: #!/bin/bash MEPATH=/usr/local/bin/test FILECOUNT=`ls... (4 Replies)
Discussion started by: Immolation
4 Replies

5. UNIX and Linux Applications

Finding the oldest file in a directory without ls

I am trying to determine the oldest and most recent files in a huge directory. I am using an ls -tr statement outside my find statement. The directory is too big and I am getting an "arg list too long" error. Is there something I can put in my find statement that doesn't create a list to... (2 Replies)
Discussion started by: hiyofjord
2 Replies

6. Shell Programming and Scripting

Finding the oldest file in a particular directory

Hi all, I am a newbie to scripting and I need your help regarding finding the oldest file in a particular directory. My intention is to remove that oldest file. Are there any options available with the "find" command to do this.. Thanks in advance for your help Pavan (4 Replies)
Discussion started by: pavan_movva
4 Replies

7. Shell Programming and Scripting

Setting Variable to oldest file in a directory

I am using a bash script to perform some automated maintenance on files in a directory. When I run the script using $sh -x script.sh <directory> the script works fine. It sets the variable to the oldest file, and continues on. However when I run the script like this $./script.sh <directory>, it... (5 Replies)
Discussion started by: spaceherpe61
5 Replies

8. Shell Programming and Scripting

how to grep the oldest file in a directory

Hi, Please help me out I want to grep the oldest file in a directory, could I use "ls" command? and how? thanx in advance (1 Reply)
Discussion started by: ericaworld
1 Replies

9. Shell Programming and Scripting

Removing the oldest file in a directory

Hi all, I need your assistance in removing the oldest file in a directory. I posted the same thread 3 days back and I got the following answer ls -1 -t | tail -1 | xargs rm which is not covering the case when there are directories older than the oldest file. So, could you please... (2 Replies)
Discussion started by: pavan_movva
2 Replies

10. UNIX for Dummies Questions & Answers

Oldest File In A Directory

I'm writing a script to find the oldest file in a directory. I know this can be done by using ls -rt | tail -1 but these are rather large directories and that can be somewhat slow since the script will be running constantly. Are there any other ways to do this that would be faster? I looked to... (2 Replies)
Discussion started by: bergerj3
2 Replies
Login or Register to Ask a Question