Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
The current version of AIX i have does not have the grep -A or -B
I was told there are grep sharewares out there that has this fuctionality. I am using the grep -E Error|Message filename
But I need to be able to capture at least 2 lines before and after.
Can anyone help me please?.
Thank you.

This:
grep -A -B
is generally associated with the GNU version of grep, i.e. Linux. You should be able to obtain it at http://www.gnu.org
Here's an earlier thread that discussed using this version of grep:
http://www.computing.net/unix/wwwboard/forum/7114.html

Here is an awk script that I call cgrep (context grep). It was originally posted by aigles, and I converted it as noted in the script comments.
Thanks to aigles for posting the original script (I think in Feb 2004).
If context areas overlap, lines will not be duplicated.
# !/usr/bin/ksh
# Script: cgrep
# Author: aigles (Jean-Pierre) from COMPUTING.NET
#
# This script was originally posted by aigles as an #!/usr/bin/awk script.
# I converted to #!/usr/bin/ksh to allow parameters to be entered in the
# form of -B3 instead of -v before=3.
#
# Usage:
# cgrep [ -Bn ] [ -An ] [ -Cn ] pattern file1 file2 ...
# -Bn : n lines to display before target line
# -An : n lines to display after target line
# -Cn : n lines to display before/after target line
# pattern : regular expression
# file1 ... : input file(s)
#
# Example:
# cgrep -C3 'ERROR' input_fileB=0
A=0
C=0while true
doif [[ $1 = -B* ]] ; then
B=${1#-B}
shift
continue
fiif [[ $1 = -A* ]] ; then
A=${1#-A}
shift
continue
fiif [[ $1 = -C* ]] ; then
C=${1#-C}
shift
continue
fibreak
done
awk -v before=$B -v after=$A -v context=$C '\
function PrintBeforeContext ( lindex, lfrom, lto) {
lfrom = before_index - before
if (lfrom < 0) lfrom = 0
lto = before_index - 1
for ( lindex = lfrom ; lindex <= lto ; lindex++ )
print before_context[lindex % before]
before_index = 0
}BEGIN {
context = context + 0
before = before + 0
after = after + 0
if (context > 0)
{before = context
after = context}
before_index = 0
before_context[0] = ""
after_index = 0
pattern = ARGV[1]
ARGV[1] = ""
if (ARGC <= 2) ARGV[ARGC++] = "-"
}$0 ~ pattern {
PrintBeforeContext()
print $0
after_index = after
next
}after_index > 0 {
print $0
after_index--
next
}before > 0 {
before_context[before_index % before] = $0
before_index++
}' $*exit 0

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

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