For a bash script I am currently developing I want to access the name of the most recently edited file (including folders but not subdirectories) in a specified directory. How do I do this?
3 Answers
As @fedorqui suggested You can do:
ls -1t | awk '{ print $9; exit}'
Old post:
You can get it using awk
and tail
ls -lrt /path/to/folder/ | tail -1 | awk '{ print $9 }'
-
Note you can improve it by using
ls -lt
(without-r
that reverses) and then skiptail -1
by doingawk '{print $9; exit}'
– user75460Commented Apr 11, 2014 at 20:02 -
-
1As per the
-l
part. You can use1
(one) instead.– user75460Commented Apr 11, 2014 at 20:08
ls -t /path/to/folder/ | sed -n 1p
-t
sorts ls by date modified. The output is piped to sed to get the first line of the output.
-
Don't You print only the third file in first column by using this
sed
command? Commented Apr 11, 2014 at 18:02 -
1@Mateusz ls, when piped, doesn't print in columns. I've made the answer much simpler though, printing the first line since if you haven't aliased ls to show hidden files etc then the first line is all that's necessary since there's no total/etc.– grg ♦Commented Apr 11, 2014 at 18:18
-
You can also do
ls -t /path/to/folder/ | head -1
which I think is slightly more readable.– sgauriaCommented Apr 11, 2014 at 21:12
Parsing ls
is helpful in most of the cases, but sometimes it is not a good idea.
To have a 100% sure solution, you can use the find
command and make it print the last time all files were accessed. By printing it in a numeric way, they you can sort the list and print the last one.
find /your/path -maxdepth 1 -print0 | xargs -0 stat -c "%Y %n" | sort -n | tail -1 | cut -d' ' -f2-
Explanation
-maxdepth 1
does not go deeper in the directory structure.xargs -0 stat -c "%Y %n"
gets the file name and prints its time of last modification plus the name of the file. (fromman stat
: "%Y time of last modification, seconds since Epoch")sort -n
orders the list numerically, being the first the oldest.tail -1
gets the last of the list.cut -d' ' -f2-
removes the printing of the datetime.
-
1There's no
-printf
operator on OS Xfind.
find: -printf: unknown primary or operator
Commented Apr 11, 2014 at 19:50 -
Oh, thanks @MateuszSzlosek Just updated with an approach with
print0
and thenxargs
. I am curious to see if it works. It should...– user75460Commented Apr 11, 2014 at 19:57 -
-
Let's try with
stat -f
as described in Last modified date of a directory in OSX– user75460Commented Apr 11, 2014 at 20:05 -