Greg Gannicott’s Blog

Ksh tip: Outputting Last Modified File

Posted in Technology by Greg Gannicott on September 24, 2008
Tags: , , , , , , ,


The following command will output the last file to be modified in the working directory:

cat `ls -lt | egrep -v ^d | tail -1 | awk ' { print $9 } '`

This command can be adapted to use commands other than ‘cat’ (eg. vi, cd, tail etc).

Why would you want to do this? Providing you are the only user using the directory, you might find you want to work on the same file. Rather than perform a ‘ls -ltr’, copy the filename and then paste it (which involves the mouse – an unnessary evil when using the command line), its good to use a set of commands that are written to work on the last updated file. I realise there are other commands around that help with this, but in the environment/shell I use at work (Ksh), these aren’t available. I have the following aliases setup in my .profile:

# VI the last modified file

alias vil='vi `ls -lt | egrep -v ^d | tail -1 | awk ' { print $9 } '`'

# Cat the last modified file

alias catl='cat `ls -lt | egrep -v ^d | tail -1 | awk ' { print $9 } '`'

# Display the last 1000 lines of the last modified file

alias taill='tail -f1000 `ls -lt |egrep -v ^d | tail -1 | awk ' { print $9 } '`'

# Change to the last modified directory

alias cdl='cd `ls -lt | grep ^d | tail -1 | awk ' { print $9 } '`'

So if I want to Vi the last modified file, I just type ‘vil’ and hit return.

These set of commands have proven to be much more useful than I first expected when writing them.

2 Responses to 'Ksh tip: Outputting Last Modified File'

Subscribe to comments with RSS or TrackBack to 'Ksh tip: Outputting Last Modified File'.

  1. kilroy said,

    alias vil=’vi `ls -lt | egrep -v ^d | tail -1 | awk ‘ { print $9 } ‘`’ should be
    alias vil=’vi `ls -lt | egrep -v ^d | head -1 | awk ‘ { print $9 } ‘`’

    • Greg Gannicott said,

      You’re quite right.

      Although my use of tail was because I really meant ‘ls -ltr’ rather than ‘ls -lt’.

      Both our fixes should work. I’ll update it when I get the chance.

      Thanks for feeding back.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: