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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to read multiple lines with awk

Status
Not open for further replies.

pnut

Programmer
Feb 2, 2000
2
US
I'm new to awk and need some help. <br>
<br>
When a string is found, using awk, how do you read and display the next 3 lines of the file if the search string is not present?<br>
<br>
Thanks!!!!
 
I found the answer, in case anyone else has hit the same stumbling block, here it is. <br>
This script will print the line in which the string is found and 2 lines after. Variables can be adjusted to print n # of lines. My search was for the first field only, however this can also be adjusted. Have fun and God bless.<br>
<br>
awk '<br>
BEGIN {<br>
flag = 0;<br>
count = 0;<br>
limit = 3<br>
}<br>
{<br>
if (( flag == 0 ) && ( $1 == &quot;string&quot; ))<br>
#<br>
flag=1<br>
#<br>
if (flag &gt; 0)<br>
{<br>
++count<br>
print<br>
}<br>
if ( count &gt;= limit )<br>
{<br>
flag=0<br>
count=0<br>
}<br>
} ' filename
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top