The way I'd approach this is using the shell's own file-finding abilities to find all candidates, then keep the newest one:
#!/bin/bash
enable ** as recursive glob, don't fail when null matches are found, and
also look into things starting with .
shopt -s globstar nullglob dotglob
newestmod=0
for candidate in /Ast//Pagination.json ; do
# check file type:
[[ -f ${candidate} ]] || continue
[[ -L ${candidate} ]] && continue
# Get modification time in seconds since epoch without fractional
# part. Assumes GNU stat or compatible.
thisdate=$(stat -c '%Y' -- "${candidate}")
# if older than the newest found, skip
[[ ${thisdate} -lt ${newestmod} ]] && continue
newestmod=${thisdate}
newestfile="${candidate}"
done
if (( newestmod )); then
printf 'Newest file: "%s"\n' "${newestfile}"
fi
or such.
In zsh
, that whole thing becomes a bit less complicated and supports subsecond precision in timestamps:
#!/usr/bin/zsh
#get the list of regular (.
) files, o
rdered by m
odification date
allcandidates=(/Ast//Pagination.json(ND.om))
if (( $#allcondidates )) print -r Newest file: $allcandidates[1]
Or just:
print -r Newest file: **/Ast/**/Pagination.json(D.om[1])
Beware that while **/
in zsh and bash5.0+ don't follow symlinks when recursively traversing the directory tree, the Ast/
part would traverse symlinks. If that were a concern, in zsh
, you could work around it with:
set -o extendedglob
print -r Newest file: ./**/Pagination.json~^*/Ast/*(D.om[1])
Where ./**/Pagination.json
finds all the files without traversing symlinks but ~pattern
removes the paths that match the pattern, here the ones that don't (^
) contain /Ast/
.
find /Temp -path '*/Ast/*' -type f -name 'Pagination.json' -exec ...
– muru Sep 13 '23 at 09:33xargs grep
) to get the most recently modified file – muru Sep 13 '23 at 09:43find
simplification really helped. But that link is harder than a simplels -lt
. – Saeed Neamati Sep 13 '23 at 09:50ls -l
output is still not that simple even with new versions of GNU ls. https://unix.stackexchange.com/q/754193/70524 ... And that reminds me that I had posted basically the samefind | sort | sed
thing years ago: https://unix.stackexchange.com/a/198050/70524 – muru Sep 13 '23 at 09:56--time-style
like in that post, and even then you have to be sure thatls
won't be invoked multiple times (because there were too many arguments, say), in which casels
would sort one set of files, then sort the next set and so on, and so a simpletail -n 1
wouldn't be sufficient. Also space is ASCII. – muru Sep 13 '23 at 10:10r
to the options of tols
. – Henrik supports the community Sep 13 '23 at 13:00ls
that each will sort it's output, but the output from the different invocations won't be mixed, so you'll effectively just the files in a random order. – Henrik supports the community Sep 13 '23 at 13:03