1

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?

2 Answers 2

2

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.

6
  • sounds good. But happens if I have the following filename: "2011-05-19.markdown; rm -rf ~"? Isn't xargs insecure? Commented May 19, 2011 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
    Commented May 19, 2011 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. Commented May 19, 2011 at 11:51
  • @queueoverflow Fair enough, I was just kidding :) Thanks for the edit!
    – slhck
    Commented May 19, 2011 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
    Commented May 21, 2012 at 14:20
1
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).

You must log in to answer this question.

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