0

I am trying to find a ways how to find last n newest files for multiple directories.

The problem with that is that the directories are structured, but not really hierarchical placed, but they have specific names. Example:

./sensor
-./motion
--./2dMotion
---./saved
----./<name>.csv
---./processed
----./<name>.csv
--./3dMotion
---./saved
---./processed
-./temp
--./saved
---./<name>.csv
--./processed

The problem for me is the following: I can use -regex option in the find command, but that can give me only newest files after further commands for search filtering newest file, but that is only valid for the latest file regardless of the sensor that is used.

What am I trying to achieve is to create output in which the latest n files would be shown based on the time stamp.

How can I do that as simply as possible?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

3 Answers3

5

For the 10 latest regular .csv files in any saved directory, on a GNU system:

LC_ALL=C find . -type f -regex '.*/saved/[^/]*\.csv' -printf '%T@:%p\0' |
  sort -rnz |
  awk -v RS='\0' -F/ '{sub(/[^:]*:/, ""); file = $0; NF--}
                      ++n[$0] <= 10 {print file}'

(the files will be listed from the newest to the oldest).

With zsh, you can also do something like:

for dir (**/saved(NDF)) print -rC1 -- $dir/*.csv(ND.om[1,10])
1
find . -type d -exec bash -c 'echo "next dir: ${1}" ; ls -lt "$1" |
    grep ^- |
    head -n 5' bash {} \;

newest from the whole tree

This turned out not to be the answer as this gives the newest files from the whole tree but it may be helpful anyway.

find . -type f -printf "%T@ %p\n" |
    sort -nr |
    awk 'NR==6 { exit; } {$1=""; print; }'
Hauke Laging
  • 90,279
0

Use ls -lt |grep '^-' |head -n N simply within a loop.

for DIR in /path/to/*; do
if [ -d "$DIR"]; then
    ls -lt "$DIR/*.csv" |grep '^-' |head -n N
fi
done

Where N is number of newest files and you can specify how number of files show in result per each directory. see man ls.

αғsнιη
  • 41,407