Ask Doctor Shell ...
This site uses stylesheets and XHTML1.1. You might want to switch to a modern browser like Firefox, Mozilla, or maybe IE6.

I want to see line number n and some lines before ...

I have a log file with command invocations and output. The interesting result is on line number $lno. I want to see this line and the preceding $lcount lines. How can I do this with head and tail?

Solution:

Simply:

head -$lno $logfile | tail -$lcount

This extracts the first $lno lines from $logfile and show the last $lcount lines of this.

Simple - isn't it?

But:

It could still be simpler!

To get the line number, you need something like grep -n .... In addition, the line number must be extracted with cut or some shell mechanics:

lno=$( set -- $(grep $pattern $logfile | head -1); echo $1)

(This runs in ksh or bash only; with the Bourne shell, you need plain ol' backticks and backslashes to protect the inner pair.)

That's a lot of work, only to get the number, so that the head / tail sequence works.

To simplify the whole procedure, forget the line number, and parse your file with sed:

sed <$logfile "/$pattern/q" | tail -$lcount

That's it!

Valid XHTML 1.1! Valid CSS!

@(#) $Id: 0005.shtml,v 1.6 2005/06/24 04:49:46 kdo Exp $