Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I write a journal and name the files in a YYYY-MM-DD.markdown fashion. When I want to amend something to the last entry, I would like to open it with a shortcut, instead of writing out the full date (bash completion does not help at all).

How can I open the last file (in alphabetical order) in vim?

share|improve this question
up vote 1 down vote accepted

If it's really the last file:

vim $(find . -type f  -maxdepth 1 | sort | tail -n 1)

Or to be more specific about markdown files:

vim $(find . -name "*.markdown" -maxdepth 1 | sort | tail -n 1)

You can of course create an alias for that in your bash profile.

alias newest='vim $(find . -name "*.markdown" -maxdepth 1 | sort | tail -n 1)'

Edited because xargs and vim causes some serious trouble after exiting it. Have to find out why this is. I also had backticks before, but using $() instead of backticks is the new way to go.

share|improve this answer
sounds good. But happens if I have the following filename: "2011-05-19.markdown; rm -rf ~"? Isn't xargs insecure? – Martin Ueding May 19 '11 at 11:40
Who would have such a file name? :) If you want to call it that way, xargs is of course insecure. But: Turns out you can't use xargs and vim together anyway. See my edited post above, this should be easier. – slhck May 19 '11 at 11:45
As I have learned on #bash, you should not ask "Who has these filenames?" but make your code secure so that it can handle it. – Martin Ueding May 19 '11 at 11:51
@queueoverflow Fair enough, I was just kidding :) Thanks for the edit! – slhck May 19 '11 at 11:53
find doesn't return sorted output, so the tail -n 1 will return the last item in the output of find which isn't necessarily the newest file. Adding a | sort after find should address this. – Burhan Ali May 21 '12 at 14:20
vim "$(ls -1 *.markdown | tail -n 1)"

Works with spaces in filenames, and does need neither find (which recurses by default, which might not be what you want) nor sort (output of ls is alphabetical by default).

share|improve this answer

You must log in to answer this question.

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