Here's a perl
implementation which doesn't rely on parsing the output of ls -l
(which is inherently unreliable), and can easily be modified to use any date or size output format required.
Save it to a file, make it executable and run it as /path/to/script /usr
. The script requires one or more directory name arguments.
#!/usr/bin/perl
use strict;
use Date::Format;
if ($#ARGV < 0) { die "Missing directory argument" };
foreach my $dir (@ARGV) {
$dir =~ s:/+$::; # strip trailing /
opendir(my $dh, $dir) || die "Can't opendir $dir: $!";
while (readdir $dh) {
next if (m/^\.{1,2}$/); # skip . and .. entries
my $mtime=(stat("$dir/$_"))[9]; # extract mtime field from stat
my $mtime_f = time2str('%Y-%m-%d %X', $mtime);
open(my $fh, "-|", 'du', '-s', '--', "$dir/$_");
my $du = <$fh>;
($du) = split(' ',$du); # only want the first blank-separated field
close($fh).
printf "%s\t%s\t%s\n", $mtime_f, "$dir/$_" , $du;
}
closedir $dh;
};
There are simpler, shorter ways of doing this (in perl or awk or other languages) but this provides a useful base for reporting other information about directories and their contents. see perldoc -f stat
for full details on the information available from the stat()
function.
BTW, this could be implemented in awk
, but you'd have to implement your own stat()
function and a date-formatting function. Easier to use perl
.
GNU awk
aka gawk
supports loadable modules and the filefuncs
module provides a stat()
which populates a statdata[]
array. Use by adding @load "filefuncs"
at the top of your awk
script.
awk
is notsh
. backticks and$()
aren't supported. Use thesystem()
function instead. – cas Aug 02 '17 at 05:31