When it comes to UNIX shell-scripting I need all the help I can get.  It’s hard trying to do something new because getting to the right info requires reading many manual pages.  Here are commands I learned to find the latest version of a file that has a timestamp in its filename.  Suppose the files are

myFile.2008-05-01.12.45.01

myFile.2008-05-01.12.46.02

myFile.2008-05-01.12.47.03

and they’re in a directory with many other files, and you want to find the myFile with latest time, then issue this command in the directory of myFile:

ls -l | awk '/myFile/ {print $NF}' | tail -n 1
 

Ok, so what does this do?

“ls -l” prints the files in the current directory, one file per line, in ascending sorted order.  This output is passed to awk, which evaluates each line, searching for the pattern myFile, and for each line with myFile, it separates the words by whitespace, and prints the last field, which is the filename.  The list of such filenames is then passed to tail -n 1, which simply prints the last file in the list.  The result should be what we want.  Of course, if there are other files such as myFileABC, then this command won’t work.  We’ll need a more specific regular expression pattern in the awk command.

Can anyone do it simpler?  Please share.  Thanks.



⊕ Related Posts

  • Personalize Your Unix Shell Prompt

  • Goosh.org:Google for the command line zealots

  • Disable shadow in screen window captures

  • “Eve firing” Adium dock icon


  • ⊕ Article Tags → | | | | | | |

    4 Responses to “UNIX command for getting the latest version of a file”

    1. Michael on July 27th, 2008 9:07 pm

      So, why not do `ls -1 myFile* | tail -n 1`?
      I’m not very familiar with awk, but from what i’m seeing your thing just looks for all things after the text myFile, and outputs the last entry. This should do the same thing.

      Also if you want to sort by the actual latest modified time, just use `ls -tr1 myFile* | tail -n 1`.
      -t for sort by time
      -r for reverse (so latest file is first)
      -1 for one element per line.

    2. Kevin on July 29th, 2008 10:00 pm

      Thanks Michael. I recall when I attempted `ls -1 myFile* | tail -n 1` within a script, the command wouldn’t expand the wildcard *, and so it resulted in looking for a file named precisely ‘myFile*’, which wasn’t what I wanted. That reminds me to investigate how to expand the wildcard * in a script.

    3. Michael Tao on August 1st, 2008 11:20 am

      Perhaps you had it wrapped in single quotes by accident? I don’t really see how anything else could have caused this.

    4. Andrew on August 1st, 2008 11:30 am

      Simple and easy way I think is as follows:

      ls -r1 | grep -e “^myFile” -m 1

      which will avoid your expansion problems.

    Leave a Reply