Operating System - HP-UX
1827595 Members
2993 Online
109966 Solutions
New Discussion

Script to find most recent file

 
SOLVED
Go to solution
Preet Dhillon
Advisor

Script to find most recent file

I need to list the full path to the latest file in a directory.
For example, if I have a dir called temp with the following files in it :

Sep 18 21:20 blue
Sep 19 21:19 green
Sep 21 21:19 yellow

I need a script to search this directory and list the most recent file it finds
in a format something like this :
Sep 21 21:19 /temp/yellow
The order of the above is not important as long as I can list the full path to
the file and the timestamp.
Is there a way of doing this?
Many thanks in advance for your support.

Regards,
Preet
Nothing succeeds like excess
7 REPLIES 7
R.Suresh
Frequent Advisor

Re: Script to find most recent file

Hi,

Did you try "ls -lt" ?

Thanks
R.Suresh.
PDLS
James R. Ferguson
Acclaimed Contributor

Re: Script to find most recent file

Hi:

Try (assuming the directory you want was /tmp):

# ls -alst /tmp|awk -v pwd=`pwd` '{print $7,$8,$9, pwd"/"$10}'' > /tmp/results

...JRF...
John Palmer
Honored Contributor
Solution

Re: Script to find most recent file

Here's a simple script that combines 'ls -lt' and 'awk' to do what you require.

It requires a single argument which is the directory that you want to list (default is the current directory) and only prints the first real 'file'.

#!/usr/bin/sh

DIR=${1:-.}

ls -lt ${DIR} | awk -v DIR=${DIR} '{if ($1 ~/^-/) {print $6 " " $7 " " $8 " "DIR
"/" $9;exit }}
James R. Ferguson
Acclaimed Contributor

Re: Script to find most recent file

Hi:

Ooops, I lost part in pasting it:

# ls -alst /tmp|awk -v pwd=`pwd` '{print $7,$8,$9, pwd"/"$10}' > /tmp/results

...JRF...

Stefan Farrelly
Honored Contributor

Re: Script to find most recent file


cd
ll -tr | tail -1 | awk -v pwd=`pwd` +'{print $6" "$7" "$8" "$9}'

This will give you the latest file modified. If you want the latest file accessed then use ll -ur instead of tr.
Im from Palmerston North, New Zealand, but somehow ended up in London...
Stefan Farrelly
Honored Contributor

Re: Script to find most recent file


oops, problems pasting also, that should read;

ll -tr|tail -1|awk -v pwd=`pwd` '{print $6" "$7" "$8" "pwd"/"$9}'
Im from Palmerston North, New Zealand, but somehow ended up in London...
Preet Dhillon
Advisor

Re: Script to find most recent file

Problem Solved !
Guys - many thanks to you all for your swift and quality responses - great stuff and much appreciated.
Nothing succeeds like excess