Wednesday, April 2, 2008

awk before and after

This is attempt number one for my friend who wanted awk based before-and-after.

It's not very interactive, and needs some command line features. The point, I guess, is that you could use this in conjunction with my colorize awk function to have context sensitive searching of words in a way that less can be useful. ETA: Oh, yeah, the point was to add "before" context to tail-f filename | grep "search" , similar to how grep does it on static files. In this case, it's more of tail -f filename | awk -f thisfile.awk, and you could also pipe that through my awk colorizer for the double whammy: context (before and after search) plus color.


BEGIN {
numlinesbefore = 3
numlinesafter = 3
needle = "search"
aftercount = -1
head = ""
tail = ""
}
{
before[numlinesbefore] = $0
for (i = 0; i < numlinesbefore; i++) {

before[i] = before[i+1]
}

if ($0 ~ needle) {
for (i = 0; i < numlinesbefore-1; i++) {
head = head "\n" before[i]
}
aftercount = numlinesafter + 1
tail = ""
print head
}
if (aftercount >= 0) {
print $0
--aftercount
}

if (aftercount == 0 ) {
head = ""
tail = ""
print "---"
aftercount = -1
}
}


Of course,this is an awk program.

No comments:

Blog Archive