6

I would like to find the most recently changed file in a directory, excluding hidden files (the ones that start with .) and also excluding directories.

This question is headed in the right direction, but not exactly what I need:

Linux: Most recent file in a directory

The key here is to exclude directories...

4 Answers 4

11

Like the answer there except without -A

ls -rt | tail -n 1

Look at man ls for more info.

To make it exclude directories, we use the -F option to add a "/" to each directory, and then filter for those that don't have the "/":

ls -Frt | grep "[^/]$" | tail -n 1
2
  • ls -rt | tail -n 1 doesn't exclude directories.
    – cwd
    Commented Oct 16, 2011 at 22:14
  • Ah okay. Changed appropriately.
    – oadams
    Commented Oct 16, 2011 at 22:48
3

This does what you want, excluding directories:

stat --printf='%F %Y %n\n' * | sort | grep -v ^directory | head -n 1
0

same one, not very clean but: ls -c1 + tail if you want => ls -c1 | tail -1

$ touch a .b
$ ls -c1
a
$ ls -c1a
a
.b
$ touch d
$ ls -c1
d
a
$ ls -c1a
.
d
a
.b
..
$ touch .b
$ ls -c1a
.b
.
d
a
..

As you can see, without a arg, only visible files are listed.

2
  • it's also showing directories - I'd hoped to exclude those. Am I using your command wrong?
    – cwd
    Commented Oct 16, 2011 at 22:16
  • ls -cF1 | grep -Ev '/$' | head -1 ?
    – Aif
    Commented Oct 17, 2011 at 8:49
0

probably the same as the answer in the other post but with a small difference (excluding directories) -

ls --group-directories-first -rt | tail -n 1
1
  • also without a '*' symbol at the end of the filename
    – ankith13
    Commented Oct 17, 2011 at 11:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.