Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I'm trying to open a file with vim from the command line, the file is in a directory filled with automatically generated files that are prepended with a time stamp. Since I don't know the time stamps off the top of my head, I would just like to open the most recent one in the directory (also the last one in the list alphabetically).

vim ./my_dir/<last_item>

Is there a way to do this?

share|improve this question
    
People are assuming that your operating system has POSIX-conformant utilities and shells. You haven't given that information, though. Does your operating system have POSIX-conformant shells and utilities? Tag your question properly. (Terminals have nothing to do with this.) –  JdeBP Dec 9 '11 at 17:12
add comment

1 Answer

This should work:

vim my_dir/$(ls my_dir | tail -n 1)

How it works:

  1. Since the result is piped, ls displays one bare file name per line.
  2. tail -n 1 only shows the last line.
  3. $(...) executes the command and appends the output to vim mydir/.
share|improve this answer
    
just a small tip, you don't need -1 passed to ls in this situation; ls chooses that output format since you use a pipe. To both @Dennis and @Lee, this is harder than it sounds, what if the last object is a directory? You can have simple, or you can have solid, not both. –  Rich Homolka Dec 9 '11 at 15:14
    
@RichHomolka: Thank you for the tip. I have updated my answer. Regarding your objection, a simple --group-directories-first should take care of directories. –  Dennis Dec 9 '11 at 15:22
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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