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

search for a regular expression, then grab another line 1

Status
Not open for further replies.

sno2003

MIS
Jan 7, 2003
1
US
I have a script where I was searching for a regular expression then grabbing the line right above it.

|awk '/regexpr/{print x};{x=$0}'

My input file has changed and now I need to grab just the 5th line above the regexpr. Any ideas?

For reference sake how do I grab the 5th line below the regexpr. Or say the first and second lines above/below the regexpr?

Thanks in advance
Dave
 
Code:
##  Works for nth >= 0.
{ lines[NR] = $0 }
/foo/ { print lines[NR-nth] }
{ delete lines[NR-nth] }
Save this code in file "nth.awk".

Run it with
[tt] awk -f nth.awk nth=5 data[/tt]
 
how do I grab the 5th line below the regexpr
|awk '
{buf[NR]=$0;n=NR}
END{for(i=1;i<=n;++i)if(buf~/regexpr/)print buf[i+5]}
'
the first and second lines above/below the regexpr?
{buf[NR]=$0;n=NR}
END{for(i=1;i<=n;++i)if(buf~/regexpr/)
print buf[i-1]"\n"buf[i-2]"\n"buf[i+1]"\n"buf[i+2]
}'

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
[tt]
# When expression is found, print specified preceding
# and following lines.
# Can handle huge files because only a small portion of
# the file is kept in an array.

BEGIN {
Sought = "^foo|^bar"
# Numbers must ascend:
LINES_TO_PRINT = "-2 0 1 3"

split( LINES_TO_PRINT, Lines_to_print )
for (i=1; i in Lines_to_print; i++)
{ num = Lines_to_print[ i ]
if ( num >= 0 )
Last = num
else
First = !First ? num : First
}
}

{ lines[ NR ] = $0
show( NR )
delete lines[ n + First ]
}

END { for (i=1; i<=Last; i++) show( NR + i ) }

function show( current, spot,i,linenum )
{ spot = current - Last
if ( (spot in lines) && lines[ spot ] ~ Sought )
{ for (i=1; i in Lines_to_print; i++)
{ linenum = current - Last + Lines_to_print
if ( linenum in lines )
printf( "%2d: %s\n", Lines_to_print,
lines[ linenum ] )
}
print ""
}
}
[/tt]
When run on this file:
[tt]
1st line before
foo
1st line after
2nd line after
3rd line after
3rd line before
2nd line before
1st line before
bar
1st line after
2nd line after
3rd line after
3rd line before
2nd line before
1st line before
foo
[/tt]
the output is
[tt]
0: foo
1: 1st line after
3: 3rd line after

-2: 2nd line before
0: bar
1: 1st line after
3: 3rd line after

-2: 2nd line before
0: foo
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top