Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. 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
    
suggest to use append time stamps at the end of files, that would make sorting easier, I suppose. It makes to read the filenames as well. Is the timestamp in string formatted or epoch, however? –  Nikhil Mulley Dec 9 '11 at 14:53

4 Answers 4

This is really a job for zsh.

vim my_dir/*(om[1])

The bits in parentheses are glob qualifiers. The * before is a regular glob pattern, for example if you wanted to consider only log files you could use *.log. The o glob qualifier changes the order in which the matches are sorted; om means sort by modification time, most recent first. The [ glob qualifier means to only return some of the matches: [1] returns the first match, [2,4] return the next three, [-2,-1] return the last two and so on. If the files have names that begin with their timestamp, *([1]) will suffice.

In other shells, there's no good way to pick the most recent file. If your file names don't contain unprintable characters or newlines, you can use

vim "$(ls -t mydir | head -n 1)"

If you want to pick the first or last file based on the name, there is a fully reliable and portable method, which is a bit verbose for the command line but perfectly serviceable in scripts.

set -- mydir/*
first_file_name=$1
eval "last_file_name=\${$#}"
share|improve this answer
    
super like, if it means an upvote :-) –  Nikhil Mulley Dec 9 '11 at 20:41

This works for me:

$ ls -rt | tail -1 | xargs vim

But you may have a directory as the last entry, in which case you might want to filter directories:

$ ls -rt | grep -v "^d" | tail -1 | xargs vim
share|improve this answer

If you are inside my_dir:

vim $(ls -rt | tail -1)
share|improve this answer
    
Better to reverse the sorting and add quotes: vim "$(ls -t | head -1)" –  enzotib Dec 9 '11 at 15:39

I guess you are looking for this.

[centos@centos temp]$ for i in `seq 100`; do touch $i; done

[centos@centos temp]$ ls -t1 | head -1
100


[centos@centos temp]$ vim /.my_dir/$(ls -t1  | head -1)

But sorting depends entirely on your filename.

share|improve this answer

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.