RegExp: From first occurrance to last (at line start)

So I have a log that contains something like this:

What I want is to get the first occurrence of "^localhost0" (at line start) and then everything else up to the last occurrence of "^localhost0" (at line start)

Ideally I don't even care about the 2 "localhost0" lines either. All I really care about is the information stored between the command and the exit call.

I cannot seem to think of a way to do this with grep... aka

Any help?

I can think of two approaches:
Store the data to display in memory while you figure out what is 'in' and what's 'out'.
Run through the file a couple of times.

As I don't know how big the file is, we'll go with the multiple passes solution - it's ugly but it has a predictable memory footprint :wink:

#!/bin/sh
first=`egrep -n "^$1" $2 | cut -d ':' -f 1 | head -1`
last=`egrep -n "^$1" $2 | cut -d ':' -f 1 | tail -1`
head -$last $2 | tail +$first | egrep -v "^$1"

usage: scriptname.sh localhost0 filename.log
If you want to keep displaying the 'localhost0' lines too, just leave off the last egrep -v

awk '/^localhost0/,/^localhost0: exit/' file

My awk's not the best but wouldn't that only print the lines between the first and second ^localhost0? Rather than the first and last?

With localhost0 lines:

awk '/^localhost0/ { min = min ? min : NR ; max = NR }  min { line[NR] = $0 } END { for ( i = min ; i <= max ; i++ ) { print line}}' file

without:

awk '/^localhost0/ { min = min ? min : NR ; max = NR }  min { line[NR] = $0 } END { for ( i = min + 1 ; i < max ; i++ ) { print line}}' file

It will print all lines between and including the lines that start with ^localhost0. Isn't that the desired output.? :confused:

Gotta be precise here :wink: