Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Printing lines before and after a match ... Help

408 views
Skip to first unread message

Ed Noble

unread,
Jul 18, 2004, 5:04:40 PM7/18/04
to
Hello all ...

Im having a heck of time trying to accomplish this task with awk.
Im not sure if this is possible, so also let me know if Im wasting my
time.
Here goes ... .. ..

Im trying to make awk print the line(s) before and after it find a
match.

This is the block of code to find the match and print the match.

awk -F"|" '$2 == widget{name[x++] = $0}
END{for(i=0; i<NR; i++)print i, name[i]}' filename
Now in addition to this, I want to print the line(s) before AND after
the matching line. Or even better be able to print 2 or 3 lines
before and after the match.
If this is possible with awk.

Please help
EN

spam...@abc.xyz.com.net.org.us

unread,
Aug 18, 2004, 7:00:49 PM8/18/04
to

Here's an example that finds a username in /etc/passwd and prints
out 2 lines before and after it. Call the script like this:
scriptname /etc/passwd

#!/usr/bin/awk -f

# Create an array containing all lines you read in.
# Careful because depending on the size of your input
# file, this could consume alot of memory.

{ all_lines[NR] = $0 }

# Remember which record number produced the match.
# Don't print anything out yet.

/^joe_username:/ {
line_matched = NR
}

# Finally, print out 2 lines before, the matched line,
# and 2 lines after.

END {
for (i=line_matched-2; i<=line_matched+2; i++) {
print all_lines[i]
}
}

If somebody knows a more efficient way, please post :)


Rufus V. Smith

unread,
Aug 23, 2004, 9:59:45 AM8/23/04
to

<spam...@abc.xyz.com.net.org.us> wrote in message
news:slrnci7nt...@ultra.localnet...

Rather than store all the lines in an array, just store the most recent
two lines (in a sort of fifo). When you hit your match, just
output those fifo lines first.

I think this should do it, though not extensively tested.

------

# program to read a file and match a line, printing out
# 2 lines prior and subsequent to the match

BEGIN { forced = 0 ; store1 = "" ; store2 = ""}

/Match/ { print "--"; print store2; print store1; forced=3 }

{ if (forced) {forced-- ;print $0};
store2 = store1; store1 = $0}


0 new messages