Hi,
I am trying to locate the occurences of certain pattern like 'Possible network disconnect' in a text file. I can get the actual lines matching the pttern using:
grep -w 'Possible network disconnect' file_name.
But I am more interested in getting the timing of these events which are located on the previous lines of those which match the pattern.
I tried some other techniques like:
while read LINE do
....
....
....
done< file_name
But could not extract the desired lines from the text file.
Can anyone help me accomplish desired results?
Thanks a million in advance.
Adjust parameter after -B, depending on how many lines before match you want to print:
grep -B5 -w 'Possible network disconnect' file_name
Hi bartus11,
Thanks for the reply, but my OS doesn't support -B option to grep.
Mine is SunOS 5.8 Generic_117350-45 sun4u sparc SUNW,Sun-Fire-V440
Regards,
Sagar
This will print matching line, then n lines that were before (in random order):
awk -vn=5 '{a[NR%n]=$0}/Possible network disconnect/{for (i in a) print a}' file_name
This one prints 5 lines before the pattern + the pattern itself:
awk '/Possible network disconnect/ { print NR }' file_name | while read line
do
awk '{ if(NR >= '$(($line - 5))' && NR <= '$line') print }' file_name
done
ctsgnb
October 24, 2010, 12:20pm
6
bartus11:
This will print matching line, then n lines that were before (in random order):
awk -vn=5 '{a[NR%n]=$0}/Possible network disconnect/{for (i in a) print a}' file_name
@bartus , could you please explain your code ?
a[NR%n] : what does the % stand for : is it the modulo operator ?
when you write
for (i in a) print a
[i]what is the initial i value : 1 ? or 0 ?
nawk '{A[NR]=$0; delete A[NR-n]}/Possible network disconnect/{for (i=NR-n;i<=NR;i++) if(A) {print A; delete A}}' n=5 infile
This will print without the preceeding lines in random order (lol at that):
awk -vn=5 '/Possible network disconnect/{for (i in a) {c++;c%=n; print a[c]} print} {a[c=NR%n]=$0} ' file_name