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?

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

3 Answers 3

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])
3
  • Hello, I have tried running you script, but error shows regarding cut command: cut: invalid option -- 'z'
    – user217392
    Aug 30, 2017 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. Aug 30, 2017 at 14:00
  • It is running without a problem
    – user217392
    Aug 30, 2017 at 14:06
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; }'
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.

2
  • 1
    That is probably not what the asker is looking for. Aug 30, 2017 at 13:20
  • @HaukeLaging Updated my answer Aug 30, 2017 at 13:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .