System Administration
cancel
Showing results for 
Search instead for 
Did you mean: 

find command: How to find the oldest file in a folder

 
SOLVED
Go to solution
Leo The Cat
Regular Advisor

find command: How to find the oldest file in a folder

Hi Guys

How to find the oldest file in a folder only with a method based on the find command ?

bests regards
Den
9 REPLIES
Steven Schweda
Honored Contributor
Solution

Re: find command: How to find the oldest file in a folder

> [...] based on the find command ?

Why use "find"?

ls -1t | tail -1
KarloChacon
Honored Contributor

Re: find command: How to find the oldest file in a folder

this work too

ls -lrt | head -2
Didn't your momma teach you to say thanks!
Steven Schweda
Honored Contributor

Re: find command: How to find the oldest file in a folder

> this work too

Try it with "-1rt" instead of "-lrt".
one ell

Unless you really want more than the name.
KarloChacon
Honored Contributor

Re: find command: How to find the oldest file in a folder

but if you really need only files and not directories

since my previous ls -lrt | head -2 list the file or directory that is the oldest or the 2 oldest if you modify head to -3 or -4 and so on


to list the oldest file only

#ls -lrt | grep -v ^d | head -2
Didn't your momma teach you to say thanks!
Steven Schweda
Honored Contributor

Re: find command: How to find the oldest file in a folder

> but if you really need [...]

As usual, what we really need most is a
complete description of the problem to be
solved.

> [...] | head -2

Still shows "total xxxx" along with the
desired information. "| tail -1" could solve
that, but then why use "head" at all?
KarloChacon
Honored Contributor

Re: find command: How to find the oldest file in a folder

ok sorry Steven sometimes I'm not perfect


#ls -gt | grep -v ^d | tail -1
Didn't your momma teach you to say thanks!
Steven Schweda
Honored Contributor

Re: find command: How to find the oldest file in a folder

Now extract only the file name. (And does
your method for that work if the file name
contains space characters?)

Everything's complicated.
James R. Ferguson
Acclaimed Contributor

Re: find command: How to find the oldest file in a folder

Hi Den:

Since this is the Linux forum, I'm going to assume that you are using the GNU 'find'. Hence, "only with a method based on the find command" you could do:

# find /path -type f -printf "%T@ %h/%f\n"|sort -k1n,1|awk 'NR==1 {print $NF}'

The name of the oldest file in '/path' will be returned with its full path and name.

Of course, I took the liberty of using 'sort' and 'awk' in a pipeline too :-)

Regards!

...JRF...
Leo The Cat
Regular Advisor

Re: find command: How to find the oldest file in a folder

Many possibilities are efficient here.
Thanks guys