You're on the right track with your choice of tools:
ls -t
is a good way to sort files ordered by time so you can pick off the latest
find
is the right tool to find files matching some pattern in directories and subdirectories
The tricky part of course is that you need some kind of grouping by filename,
and pick the latest file in each group.
Because of this requirement,
I think you need a loop,
where you iterate over each target filename to find its latest version.
Assuming the files are in $dir1
, $dir2
or $dir3
,
you could write a function to find the latest version of some pattern like this:
find_latest() {
pattern=$1
ls -t "$dir1/$pattern" "$dir2/$pattern" "$dir3/$pattern" | head -n 1
}
Then let's say if you have the patterns access.log
, error.log
, x*
,
then you can loop over them like this, for example:
for pattern in access.log error.log 'x*'; do
latest=$(find_latest 'a*')
echo $latest
done
If the above assumption is not true,
and the files can be in subdirectories of $dir1
, $dir2
or $dir3
,
then you need to use find
, it gets a bit more complex:
find_latest() {
pattern=$1
find "$dir1" "$dir2" "$dir3" -name "$pattern" -print0 | xargs -0 ls -t | head -n 1
}
There's a small caveat: if a path contains newline characters,
this function won't work well because the head -n 1
step will chop off the part of the path after the newline. I cross my fingers that you don't have such paths ;-)
DIR1/FileA
withDIR2/FileA
: if you changed contains of newer file, and newer file has been changed afer old file you canfind
orstat command
.