How to sort find results

David Fleck david.fleck at mchsi.com
Mon Nov 7 19:32:18 GMT 2005


On Mon, 7 Nov 2005, Jeffrey Ellis wrote:
> Well, at least I know it can do it now. The problem -- as usual for a newbie
> -- is that I haven't got the vaguest understanding of what I just read. The
> field part I think I get, but how would I use the first character? I guess
> I'm basically too stupid to get these kind of instructions -- maybe just one
> example for the use of each option included in man pages would help?

Here's a completely different approach.  I ran into this exact problem 
often enough that I wrote a small Perl script to handle it:

#!/usr/bin/perl

use strict;
use File::Find ();

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name/;
*name   = *File::Find::name;

(@ARGV) or usage();

my (%files, $tString, $reverse);

$reverse = 1 if ($ARGV[1] =~ /r.*/);

# Traverse desired filesystems
File::Find::find(\&wanted, $ARGV[0]);

# sort %files by mod. time, print.
if ($ARGV[1] =~ /r.*/) {
     foreach my $f (sort { $files{$b} <=> $files{$a} } keys %files) {
         # chop off day of week
         ($tString = scalar localtime($files{$f})) =~ s/\w* //;
         print $tString, "\t",$f,"\n";
     }
} else {
     foreach my $f (sort { $files{$a} <=> $files{$b} } keys %files) {
         # chop off day of week
         ($tString = scalar localtime($files{$f})) =~ s/\w* //;
         print $tString, "\t",$f,"\n";
     }
}
exit;


sub wanted {
     my (@fstat);
     # put the filename and mod. time into %files
     ((@fstat) = lstat($_)) && -f _ && ($files{$name} = $fstat[9]);
}

sub usage {
     print "\n",
     "Usage: $0 (directory) [reverse]\n",
     "  examines all files in (directory) and all its subdirectories,\n",
     "  sorts by date, and returns the sorted list, earliest first.\n",
     "  If 'reverse' is specified, files are sorted earliest last.\n\n";
     exit;
}


--
David Fleck
david.fleck at mchsi.com



More information about the freebsd-questions mailing list