|
|
Selecting the Most Recent File in a Unix Directory
By Praveen Puri
We can combine two unix commands, ls and tail, to always select the most recent file in a directory. This comes in very handy if you are debugging and running a program multiple times, thus constantly creating new log files.
ls -rt will list the files in the current directory, sorted by ascending time. So, the most recent files will be listed last.
This command by itself is valuable in directories that contain lots of log files. When you use this command, the old files will scroll off the screen, and you will always see the most recent files.
tail -n will take text as input and display the last n lines. So, for example, tail -1 will display the last line of text.
We can combine the above two commands by using the pipe symbol (|) to feed the output of one command to another.
Thus, ls -rt | tail -1 will print the name of the most recent file in a directory.
We can always add qualifiers to the ls command, so:
ls -rt *.log | tail -1
will list the most recent log file in the directory.
Now, we can make this more valuable by using back ticks (') to run this command , and then feed the output as arguments for another command, such as the vi editor.
Thus, vi `ls -rt *.log | tail -1` will load the most recent log file into the editor.
This can be very helpful, when you have log files with long names composed of date and time stamps, such as:
Server.14005.05132007-110844.log
Server.14005.05202007-110844.log
Server.14005.05272007-110834.log
Server.14005.06032007-110835.log
If we keep running the Server command, and want to keep viewing the latest log file in the editor, we do not have to keep figuring out which log file is the latest, and then typing vi and the file name.
Instead, we can just keep running vi `ls -rt *.log | tail -1`.
Praveen Puri has been a unix programmer for the last 17 years. He has a blog called Unix Simplicity that is dedicated to unix shell scripting and awk programming.
Article Source: http://EzineArticles.com/?expert=Praveen_Puri
SunitesLounge // Blogging Information & Resources is a Blog devoted to blogging.
From blogging information to blogging resources and interesting sites.
