2

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 3

2

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 }'

3
  • Note you can improve it by using ls -lt (without -r that reverses) and then skip tail -1 by doing awk '{print $9; exit}'
    – user75460
    Commented Apr 11, 2014 at 20:02
  • ls -lt gives "total XXXX" on the first line. Commented Apr 11, 2014 at 20:06
  • 1
    As per the -l part. You can use 1 (one) instead.
    – user75460
    Commented Apr 11, 2014 at 20:08
1
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.

3
  • 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.
    – sgauria
    Commented Apr 11, 2014 at 21:12
0

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. (from man 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.
5
  • 1
    There's no -printf operator on OS X find. find: -printf: unknown primary or operator Commented Apr 11, 2014 at 19:50
  • Oh, thanks @MateuszSzlosek Just updated with an approach with print0 and then xargs. I am curious to see if it works. It should...
    – user75460
    Commented Apr 11, 2014 at 19:57
  • stat: illegal option -- c Commented Apr 11, 2014 at 20:02
  • Let's try with stat -f as described in Last modified date of a directory in OSX
    – user75460
    Commented Apr 11, 2014 at 20:05
  • -print0 option gives me concatenated output of ls Commented Apr 11, 2014 at 20:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .