ysrinu
October 16, 2008, 12:15pm
1
Hi,
how can i print the previous, current and next line using sed?
current line is the matching line.
The following prints all lines containing 'Failure' and also the immediate next line
cat $file | sed -n -e '/Failure/{N;p;}'
Now, i also want to print the previous line too.
Thanks,
-srinivas yelamanchili
sed -n -e '/Failure/{x;1!p;g;$!N;p;D;}' -e h inputfilename
ysrinu
October 16, 2008, 2:07pm
3
Thanks Jim, this worked.
-srinivas
Another option would be to use grep
grep -n -C1 Failure filename
-Prathap
If your grep version (GNU) supports the -A and -B option:
grep -A 1 -B 1 'Failure' file
Regards
sed -n '/pattern/ !{
h
}
/pattern/ {
N
H
x
p
}' filename
ysrinu
December 8, 2008, 2:37pm
7
Thanks to all for the solution.
-A, B, C options are not supported.
Using HP-UX 11.11
Now, can i print just the previous line and the matching line?
cat replace_all* | sed -n -e 'N;/Failure/p;'
prints the previous line only for the first match, thereafter only matching lines are printed and not their previous lines.
Thanks,
-srinivas
use awk its easy
awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=1 a=1 s="pattern" filename
Or:
awk '/Failure/{print s "\n" $0;getline;print;exit}{s=$0}' file
Regards