0

How can I open all and only the n (e.g. 5) most recently modified files in a directory in less or vim?

I know I can use ls -t to sort the output from most recent to oldest. So my intuition would be to use ls -t | head -5 | vim but that doesn't work since ls output is treadted by vim as raw text not filenames.

How do I do this with find? My problem with find is that I always use ls to browser directories, so know how to use it - but find I never use for that purpose.

1 Answers1

5

You really want the shell to select those filenames, in case any of the filenames contain characters from $IFS, usually space, tab, or newlines. You can work around this by asking (GNU) find utility to find the files and separate their filenames with NULLs then using the (GNU) xargs utility to separate those filenames back into less or vim, but I think it's simpler to just use a shell that can generate the filenames natively:

zsh -c 'vim *(om[1,5])'

This invokes zsh with a single vim command with a wildcard that expands to the five most recently modified files in the current directory. Those filenames are safely provided as separate arguments to vim -- they aren't further split by $IFS.

See more examples at: Find latest files, Is it possible to reference the most recently modified file in a command line argument?, and Access the most recent file in (alphabetically sorted) directory

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Thanks! I found the explanation for what this *(om[1,5]) construct does in a referenced answer: https://unix.stackexchange.com/a/26495/377222 So even if I use fish, there's no harm in using zsh just for this one command, right? – Cornelius Roemer Sep 28 '21 at 21:37
  • 2
    Right! That's why I demonstrated it with the zsh -c ... format. – Jeff Schaller Sep 28 '21 at 22:01
  • 1
    Thanks, I can see that now, but when I first saw zsh my intuition was: oh no, I use fish, what now? – Cornelius Roemer Sep 29 '21 at 12:39