views:

18

answers:

1

I have a program that outputs a logfile with a filename that changes each time it runs, so that I can keep permanent records for each run session.

Is there any utility like "less" that I can use to display the last N lines of the file that has changed most recently?

edit: the most value to me is if I have something that will automatically transition from one file to the next, so I don't have to manually stop "less" and restart it. (if I do that, I might as well type in the filename myself)

+1  A: 

There's no one command to do it, but chaining together a couple of simpler commands can get us there. This will give you the most recently modified file:

# Sort by modified time, display the first file.
ls -t <dir> | head -1

You can pass that file name to less to view it interactively, or tail if you want to see just the last few lines. tail -n <N> displays the last N lines of a file. Here are two equivalent ways to get that file name to tail:

# Use xargs to pass file name as argument to tail.
ls -t <dir> | head -1 | xargs tail -n <N>

# Use $(...) to do the same as above.
tail -n <N> "$(ls -t <dir> | head -1)"

The final piece of the puzzle is to get this to continuously monitor the directory and show whatever the newest log file is. For that we can use the watch command, which repeats a command of your choice at a regular interval.

# Repeat the above tail command every 5 seconds.
watch -n 5 'ls -t <dir> | head -1 | xargs tail -n <N>'
John Kugelman
that helps a little bit, but I really need something that keeps viewing the most recently modified file, and switches from one file to the next.
Jason S
@Jason Ah, okay, gotcha. Updated answer.
John Kugelman
OK thanks. I'll try. This is windows so I'll need to grab the gnu unxutils, but it looks simple enough.
Jason S