Print 2 matching pattern

How to a first 3 lines lines that matches 1st pattern and 1 line that matches 2nd line.

Sample.txt

Line 1: /*--- ABC_BA_ABCABC -----*/
Line 2:
Line 3: insert_job: ABC_BA_ABCABC job_type: BOX
Line 4: blah blah
Line 5: max_run_alarm: 5
Line 6: blah blah
----
-----
Line 20: /*--- BCD_CA_BCDBCD -----*/
Line 21:
Line 22: insert_job: BCD_CA_BCDBCD job_type: CMD
Line 23: blah blah
Line 24: blah blah
Line 25: blah blah
Line 26: max_run_alarm: 5
Line 27: blah blah
--
--
--
Line 50: /*--- CDE_CA_CDECDE -----*/
Line 51:
Line 52: insert_job: CDE_CA_CDECDE job_type: CMD
Line 53: blah blah
Line 54: blah blah
Line 57: max_run_alarm: 5
Line 58: blah blah

I could get first 3 lines using grep -B 3 'insert_job'
The lines between 1st pattern and 2nd pattern are not consistent.

Need output as shown below

Line 1: /*--- ABC_BA_ABCABC -----*/
Line 2:
Line 3: insert_job: ABC_BA_ABCABC job_type: BOX
Line 5: max_run_alarm: 5

Line 20: /*--- BCD_CA_BCDBCD -----*/
Line 21:
Line 22: insert_job: BCD_CA_BCDBCD job_type: CMD
Line 26: max_run_alarm: 5

Line 50: /*--- CDE_CA_CDECDE -----*/
Line 51:
Line 52: insert_job: CDE_CA_CDECDE job_type: CMD
Line 57: max_run_alarm: 5

Ignore Line#n. That is to show that the lines between pattern 1 and pattern 2 are not consistent

Appreciate your help.

how about:

awk '/[/][*]---/,/insert_job/;/max_run_alarm/{print $0 ORS}' myFile
2 Likes

Note: it is best to escape the / inside the square bracket expression when used inside a regex constant, to prevent it from being confused with the closing / of the regex constant. Some awks cannot handle that.

awk '/[\/][*]---/,/insert_job/...

or

awk '/\/[*]---/,/insert_job/...

or

awk '$0~"/[*]---",/insert_job/...
2 Likes

Ignoring the line numbers is OK, but right now there is a number, then a colon and then a space. Only then the text begins. I am not sure if the space is in your data or not, but suppose it isn't. If it is there you will have to adjust the following regexps accordingly.

sed -n '/^\/\*---/ {N;N;p};/^max_run_alarm:/p' /path/to/your/file

Your partial solution with grep -B should be avoided: "-B" is a non-standard extension to the standard grep and you can never be sure if the grep version of every system is able to understand that. It is a hard (and usually painful) lesson you learn from administrating large datacenters with hundreds or even thousands of various systems that you stick to the standards religiously because that is basically what system is "guaranteed to understand".

I hope this helps.

bakunin

2 Likes

Thank you - vgersh99, Scrutinizer, bakunin

Earlier I had to do it in 4-5 steps. Now I can do it in 1 easy step, thanks to you all