Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I want to be able to search for a string in a text file and pull out the line that matches my string and also a number of lines immediately before the string line.
For example, if I have the file test.log whose content are:13: ]<1111111>
42: ]<1111111>
43: ]<1111111>
52: ]<1111111>13: ]<2222222>
42: ]<2222222>
43: ]<2222222>13: ]<3333333>
42: ]<3333333>
43: ]<3333333>
52: ]<3333333>I want my output to only contain the blocks that have a '52:' entry present, so my output should look like this:
13: ]<1111111>
42: ]<1111111>
43: ]<1111111>
52: ]<1111111>
13: ]<3333333>
42: ]<3333333>
43: ]<3333333>
52: ]<3333333>I have used:
ex -R filename <<!
g/52: ]/.-4,.+3p
q
!which will give me the previous 4 lines from where it finds '52: ]'. But 'ex' will only work on files up to a max size of approx 5505 KB.
The log file Im working on can reach sizes of 507,975 KB! I have tried to find a solution using 'AWK' but this hasnt worked out. 'grep' is not an option as it takes way too long and it will just give me the blocks that dont include '52:'.
Thanks in advance!

I should also add that I cannot use the grep '-A' or '-B' flags with my OS as they are not recognized on my version!

Maybe you can use Steven's "Context" script located here:
http://www.unixreview.com/documents...
It was developed for those not using the GNU grep command.

perl -00 -ne 'print if /52: \]/' test.log
or
perl -00 -ne "if(/52: \]/){s/\n$//; print}" test.log
=========================================================

Thanks for the replies. Im getting a 'Servlet Exception' error from the link http://www.unixreview.com/documents...
I think I have found a solution using AWK:
awk "\$0 ~ /52: ]/ {
cmd=\"awk 'NR>=\" NR-4 \" && NR<=\" NR+2 \"' test.log\"
system(cmd)
}" test.logThe following 'sed' also works but I cannot get my head around how or why it works! Its not customizable enough for me! sed is very tricky...
sed -e '
1{$!N;$d;}
$!N;/52: ]/!D
$!N;$d;N;p
g;$!N;$d;N;D
' test.logThanks again.

>>Thanks for the replies. Im getting a 'Servlet Exception' error from the link
http://www.unixreview.com/documents...
Seems to be working now. Hey, it's the internet :)

![]() |
![]() |
![]() |

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |