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!

Reverse search query

Status
Not open for further replies.

ranjit

Technical User
Apr 14, 2000
131
GB
[tt]
Could someone please assist with the following problem.
Search file for the string ##EVENT### and print the 2 previous lines, as per the desired output:

Input file:
AAA-BBB-C-CC1FIN7438
AAA-BBB-C-CC2FIN222831
AAA-BBB-C-CC3FIN222832
##EVENT###
AAA-BBB-CCC1PROD48408
AAA-BBB-CCC3PROD4843
AAA-BBB-CCC4PROD4084
##EVENT###
AAA-BBB-CCC1TEC803083202
AAA-BBB-CCC2TEC4893
AAA-BBB-CCC3TEC325
AAA-BBB-CCC4TEC4336
##EVENT###
BLANK-----#
BLANK-----#
##EVENT###

Desired ouptut:
AAA-BBB-C-CC2FIN222831
AAA-BBB-C-CC3FIN222832
AAA-BBB-CCC3PROD4843
AAA-BBB-CCC4PROD4084
AAA-BBB-CCC3TEC325
AAA-BBB-CCC4TEC4336
BLANK-----#
BLANK-----#
[/tt]
 
And what have you tried so far ?

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ181-2886
 
[tt]
Thanks for the solution. My approach was rather clumsy...that is, reversing the file order (sending the output to a temp file) and then using something like:
$0 ~ /##EVENT###/ {
getline
{
for(i=1;i<=2;i++) {
printf("%s\n", $0)
getline
}
}
}

However it didn't work in all cases.

[/tt]
 
Hi

Nice try, ranjit. Your only mistake was using the [tt]getline[/tt] one time more then needed :
Code:
/##EVENT###/ {
  for(i=1;i<=2;i++) {
    getline
    print
  }
}
And do not call your code clumsy. It is a good start. Ok, maybe is not the optimal one. But there are uglier solutions too, for example in [tt]sed[/tt] :
Code:
sed -n '/##EVENT###/{g;p};x;s/.*\n//;x;H' /input/file

Feherke.
 
Many thanks Feherke for the assistance.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top