Arun Kurian Arun Kurian - 1 year ago 50
Linux Question

Search for combination and pattern of strings

Need help on a part of the bash script and it needs to find a particular pattern string. A sample string is given below:

//*-----------
//* %%SET %%ABC = %%BLANK
//* %%SET %%RESTART = %%BLANK7
//* %%SET %%DANGO= 236985
//*-----------
//* %%IF %%ODATE EQ 123456
//* %%SET %%ABC= GSG34
//* %%SET %%RESTART = RESTART
//* %%ENDIF
//*-----------
//* %%IF %%ODATE EQ 463123
//* %%SET %%DANGO= 236985
//* %%ENDIF
//*-----------
//* %%IF %%ODATE EQ 15641
//* %%SET %%RESTART = %%BLANK7
//* %%ENDIF
//*-----------



  • I need to find the combination of ODATE,ABC,RESTART within an IF and ENDIF condition

  • I specificly need to check beween IF and ENDIF. Also it should check for a condition that the three parameter ODATE,ABC and RESTART exist between the IF and ENDIF. If the condition is satisfied then it should print those.

  • I tried the below commands




cat file | sed -n '/%%IF/,/%%ENDIF/p'


//* %%IF %%ODATE EQ 123456
//* %%SET %%ABC= GSG34
//* %%SET %%RESTART = RESTART
//* %%ENDIF
//* %%IF %%ODATE EQ 463123
//* %%SET %%DANGO = 236985
//* %%ENDIF
//* %%IF %%ODATE EQ 15641
//* %%SET %%RESTART = %%BLANK7
//* %%ENDIF


I only need to find below:

//* %%IF %%ODATE EQ 123456
//* %%SET %%ABC= GSG34
//* %%SET %%RESTART = RESTART
//* %%ENDIF


How would I be able to do this?

Answer Source

You may use the following awk command:

awk '/%%ODATE EQ 123456/{p=1}/ENDIF/&&p{p=0;print}p' file

Output:

//* %%IF %%ODATE EQ 123456
//* %%SET %%ABC=   GSG34
//* %%SET %%RESTART = RESTART
//* %%ENDIF

Basically awk prints a line here when the variable p is true. p will set to when the line ODATE EQ 123456 appears and reset on the next ENDIF. The ENDIF itself will get printed too.


Following your comment below, you can use this command:

awk '/IF/&&/ABC/&&/RESTART/' RS='//\\*---+\n' 

The key here is the record separator RS.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download