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