1

I learned thanks to you, how to display only the last line of a listing,e.g.

ls -ltr | sed '$!d'

Now I thought, how to combine it with the find command, in order to repeat this onto each directory exitent, but I got only to a false solution:

find / -type d | xargs ls -ltr | sed '$!d'

If i read it right, this would not display the last line of each directory, but only the last line of all listings of all directories.

How to do it right ?

2 Answers2

2

Probably this would be better: combination of find and shell

find / -type d -print0 | while read -r -d '' dir; do 
    ls -ltr "$dir" | sed '$!d'
done

find will output each directory found, using the null byte instead of a newline to separate them. This stream is fed into a while loop, using read -d '' to extract each null-delimited directory name. Then, for each directory, all but the last line of ls output is deleted by sed.

The key is that the while loop iterates over each directory name, so the most recent file is found for every directory.

One big problem with this is that ls -l output does not show you the directory name, so the output probably won't make much sense -- you see files but without knowing which directory they appear in.

To find the newest file in each directory, I would do this:

find . -type f -printf "%h:%T@:%p\n" |
sort -t: -k1,1r -k2,2nr |
awk -F: '!seen[$1]++ {print $3}'
  • find to get the directory, mod time, and path name
  • sort to group by directory and sort by time
  • awk to print the pathname that is the first for each directory
glenn jackman
  • 85,964
2

I'd use this kind of construct as a starting point

find / -type d -print0 | xargs -0 -I'{}' sh -c 'ls -ltr {} | tail -1'

Caveat: it doesn't like empty directories (total 0 is output).

Chris Davies
  • 116,213
  • 16
  • 160
  • 287