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:


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?

  • Are you looking for the newest n files per directory or for the newest n from the whole tree? – Hauke Laging Aug 30 '17 at 13:19
  • Hello, I am looking for the newest files per directory – user217392 Aug 30 '17 at 13:22
  • 1
    you're looking for the newest N csv files in the "saved" directories? – Jeff Schaller Aug 30 '17 at 13:23
  • @JeffSchaller exactly – user217392 Aug 30 '17 at 13:25

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

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(ND/)) {
  (($#newest)) && printf '%s\n' $newest
| improve this answer | |
  • Hello, I have tried running you script, but error shows regarding cut command: cut: invalid option -- 'z' – user217392 Aug 30 '17 at 13:48
  • @user217392, yes you need a recent version of GNU cut for the -z option, I've updated it to remove the cut and do cut's job in awk. – Stéphane Chazelas Aug 30 '17 at 14:00
  • It is running without a problem – user217392 Aug 30 '17 at 14:06
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; }'
| improve this answer | |

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

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

| improve this answer | |
  • 1
    That is probably not what the asker is looking for. – Hauke Laging Aug 30 '17 at 13:20
  • @HaukeLaging Updated my answer – αғsнιη Aug 30 '17 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.