Print text between (and including) two delimiters on a line

awkcutsed

What's the best way to print the text between (and including) the first pattern ("SELECT" or "SSELECT") and a second pattern ("[") using a command-line took (e.g. cut, sed, awk)?

For example, given the following:

 54001744  KB035928      20  /dev/pts/8      SELECT PRINTER.LOCS WITH SHIP.TICK.BR = "15" [ INP @ 0x67E ]
 26083642  RV091101      25  /dev/pts/14     SSELECT PRODUCT BY STK.LN.SEQ [ MENU.SELECT @ 0x10C ]
 57082018  hajohug     0xACEBF1C1  SELECT ORDER.QUEUE WITH &INDEX&.STATUS = "S~S]" "H~S]" "A~S]" "M~S]" AND WITH &INDEX&.SBR "51 17~]" [ SOE.PH.ORDER.PRINT @ 0x384 ]
 50266386  hajohug     0xACEBF2F0  SSELECT UD.VIEWS WITH &INDEX& = "ORDERENTRY.ORDERENTRY~0" [ SOCKET.READ @ 0x168 ]

The result should be:

SELECT PRINTER.LOCS WITH SHIP.TICK.BR = "15"
SSELECT PRODUCT BY STK.LN.SEQ
SELECT ORDER.QUEUE WITH &INDEX&.STATUS = "S~S]" "H~S]" "A~S]" "M~S]" AND WITH &INDEX&.SBR "51 17~]"
SSELECT UD.VIEWS WITH &INDEX& = "ORDERENTRY.ORDERENTRY~0"

I've tried using cut, but I haven't been able to get things looking right.

Best Answer

To exactly match the final sequence in square brackets:

perl -alne 'm/S?SELECT.*?(?=\[ \S+ @ \S+ \]$)/ && print $&;' file

outputs

SELECT PRINTER.LOCS WITH SHIP.TICK.BR = "15" 
SSELECT PRODUCT BY STK.LN.SEQ 
SELECT ORDER.QUEUE WITH &INDEX&.STATUS = "S~S]" "H~S]" "A~S]" "M~S]" AND WITH &INDEX&.SBR "51 17~]" 
SSELECT UD.VIEWS WITH &INDEX& = "ORDERENTRY.ORDERENTRY~0" 
Related Question