Link to home
Start Free TrialLog in
Avatar of samabdelhamid
samabdelhamid

asked on

Recursive Grep between two words and print on matched word

Hi All,
I've tried this a few different ways however cant seem to work it out.

Given this input file : "$newContents"
Calibre/Item:  Shotgun Shell Holder
Make:  Red Quoll
Model:  Black
Condition:  New
Price:$50
http://Product.aspx?p=24585

Calibre/Item:  Shotgun Shell Holder
Make:  Red Quoll
Model:  DCPU
Condition:  New
Price:$50
http://Product.aspx?p=24584

Calibre/Item:  Reloading
Make:  Remington
Model:  357 cases and dies
Condition:  Excellent
Price:$320
State: NSW
http:///Product.aspx?p=24655

Calibre/Item:  30-06
Make:  Ruger
Model:  M77 Mk.II
Action:  Bolt repeater
Scope/Sights:  Zeiss 3-9x40
Condition:  Excellent
Price:$1200
http:///Product.aspx?p=24654

Calibre/Item:  222 Rem Mag
Make:  Sako
Model:  L461
Action:  Bolt repeater
Scope/Sights:  Sako rings
Condition:  Good
Price:$1500
State: QLD
http://Product.aspx?p=24653

Calibre/Item:  9mm
Make:  STI
Model:  Custom 1911
Action:  Semi auto
Barrel Length:  152mm Holland Precision
Condition:  Excellent
Price:$2800
http:///Product.aspx?p=24652

Open in new window


Lets say I want to dispaly all the lines between "Calibre/Item" and "http" if  "9mm" is found.
I am using this, which works perfectly

awk '/Calibre\/Item:  9mm/,/http/'  $newContents >>  outputfile.txt


However, When I need to search for "Make" which is the second line in the block, I still need to display everything from "Calibre/Item" and "http". However I can't use awk (becuase I'm not searching for 9mm any more).
SO I've been doing this.

grep -i -B1 -A6 'STI'    $newContents >>  outputfile.txt

I'd like to have a generic grep/awk/sed whatever, where no matter which line in this block
I searched :

Calibre/Item:  9mm
Make:  STI
Model:  Custom 1911
Action:  Semi auto
Barrel Length:  152mm Holland Precision
Condition:  Excellent
Price:$2800
http:///Product.aspx?p=24652

It would always display the contents between "Calibre/Item" and "http"

I want to be able to match text on any line : "Custom1911", "$2800", "Semi Auto"

Etc.
ASKER CERTIFIED SOLUTION
Avatar of wilcoxon
wilcoxon
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of samabdelhamid
samabdelhamid

ASKER

Excellent!
Works a charm. Just had to replace the double quote with a single quote after '/regex/'

THank you

perl -ne 'BEGIN { $/ = "\n\n" } print if /regex/' inputfile > outputfile

Open in new window

for text in 'Custom1911' '$2800' 'Semi Auto' ; do perl -00 -ne 'BEGIN{$r=shift};print if /\Q$r\E/' "$text" $newContents  >>  outputfile.txt ; done
Sorry, I don't remember seeing an answer when I posted.