Tuesday 9 July 2013

print current previous next line for the context grep in a file

this is the simplest way i believe to get the previous,current, next line for content searched in a file

 #  perl -e 'while($line=<>) {if(!$found){if(grep(/netdump/,$line)){$curr=$line;$found=1;}else{$prev=$line;}}else{$next=$line;print $prev,$curr,$next;;last;}}' < /etc/passwd
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
netdump:x:34:34:Network Crash Dump user:/var/crash:/bin/bash
nscd:x:28:28:NSCD Daemon:/:/sbin/nologin
 #