Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Do function 1

Status
Not open for further replies.

mrr

Technical User
May 3, 2001
67
US
Can someone give me a short awk example of how to:
use a loop to print records once an if condition is met,
read the next specified number of lines and print records.

such as: if ($1 = "a") { print 4 records including the a record }

a
sdfsdf
sdfsdf
sdfsdf
b
sdfsd
sdfsdf
sdfs

output would be
a
sdfsdf
sdfsdf
sdfsdf
 
$1 == "a" {
print $1
for(i=1; i <=3; i++) {
getline; print;
}
next;
} vlad
+---------------------------+
|#include<disclaimer.h> |
+---------------------------+
 
Did you want a function?

function test_n_get(subj,pat,n, i)
#subj = $NR
#pat = pattern to look for
#n = number of lines to read


if (subj ~ pat) {
do {
++i;
getline ; print
} while (i < n)
}
return
}

{
test_n_get($0,&quot;PATTERN&quot;,3)
}
 
awk '{ if ( $1 ==&quot;a&quot; ) flag=1; if ( $1 == &quot;b&quot; ) flag=2 ; if ( flag == 1 && $1 ==&quot;a&quot; ) printf(&quot;%s\n&quot;,$0); if ( flag == 1 && $1 !=&quot;a&quot; ) printf(&quot;%s\n&quot;,$0); }'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top