I need to view 5 line before grep output.
I used the command,
grep -B 5 pattern filename
But was thrown with the error /usr/bin/grep: illegal option --B
How to handle this situation and to view 5 lines before grep statement?
I need to view 5 line before grep output.
I used the command,
grep -B 5 pattern filename
But was thrown with the error /usr/bin/grep: illegal option --B
How to handle this situation and to view 5 lines before grep statement?
Have you considered using awk
?
If it is a viable option, check this one, long, line:
$ awk '/PATTERN/{for(i=1;i<=x;)print a[i++];print}{for(i=1;i<x;i++)a[i]=a[i+1];a[x]=$0;}' x=5 file
The above command will return the five lines before the matched pattern and the matched pattern (i.e. 6 lines in total whereas grep -B 5
returns five lines in total including the matched one).
x
designates the number of lines
I hope this helps.
Simply_Me's answer is correct but copies all previous lines on each non-match. (nit picking technicality: even if gawk's implementation avoids copying the strings themselves it still would have to re-hash the index). So, still sticking with awk:
#!/usr/bin/awk -f
BEGIN { cl=1; }
/foo5/ {
for (i=cl; i<cl+N; i++)
print pLines[i % N];
cl=1;
}
{ pLines[cl % N] = $0; cl = cl + 1; }
cl stands for current line. If we have a match we print N lines we stored in pLines array before. You may wish to print the pattern itself, which I didnt. Regardless of seeing the pattern, we store the line we just processed in pLines with the % operator, so we do not have to shift the array.
For
zoo0
blah1
foo2
bar3
hehe4
lisp5
foo5
blah6
foo7
bar8
hehe9
foo5
This prints
blah1
foo2
bar3
hehe4
lisp5
foo5
blah6
foo7
bar8
hehe9
which is the previous 5 lines not including the pattern.
It also works reasonably on
hehe4
lisp5
foo5
blah6
foo7
bar8
hehe9
foo5
where there is no 5 previous line before the first match of foo5. In this case it prints empty lines. You may need to tailor that for your needs.