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 ?

  • 1
    I think report of your listing via -l make problem for you , you can eliminate -l and use |wc -l for test Mar 26, 2015 at 22:49

2 Answers 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).


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'

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
  • thank you for the code, though I do not understand it in detail Mar 26, 2015 at 23:01
  • Any part in particular? Mar 27, 2015 at 1:11
  • I do not understand how the while loop works with sed '$!d', so that sed is applied to each listing of each folder every time though it looks like it would be applied only once because it is the last in the pipe-chain. Mar 27, 2015 at 1:55

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.