in reply to grabbing previous line in a log


This is a simple one-liner:     perl -ne 'print $prev, $_ if /foobar/; $prev = $_' file

However, if there are several consecutive matches it will print duplicated data.

This one doesn't produce duplicates:

perl -ne 'BEGIN{$re=qr/foo/}if(/$re/){print$p if$p!~/$re/;print$_} +;$p=$_' file

If you have a grep that supports it you can also do this:

    grep -B 1 foobar file

And finally, this is a more generalised method of printing a matched line and the n-1 previous lines, with and without duplicates:

perl -ne '$i=$.% 2; $a[$i]=$_; print @a[$i+1..$#a,0..$i] if /foo/' + file perl -ne '$i=$.% 2; $a[$i]=$_; print @a[$i+1..$#a,0..$i] and @a=() + if /foo/' file

--
John.

Replies are listed 'Best First'.
Re: Re: grabbing previous line in a log
by adonai (Initiate) on Aug 15, 2002 at 14:37 UTC
    Thanks works great!