Grab nth occurence in between two patterns using awk or sed

Hi ,

I have an issue where I want to parse through the output from a file and I want to grab the nth occurrence of text in between two patterns preferably using awk or sed

! TICKET NBR : 1 !GSI : 102 ! 3100.2.112.1 11/06/2013 15:56:29 ! 3100.2.22.3 98 ! 3100.2.134.2 8 !
! TICKET NBR : 2 ! GSI : 102 ! 3100.2.112.1 11/06/2013 16:00:45 ! 3100.2.22.3 65 ! 3100.2.134.2 3 !
! TICKET NBR : 3 ! GSI : 102 ! 3100.2.112.1 11/06/2013 16:00:45 ! 3100.2.22.3 45 ! 3100.2.134.2 6 !

Let's just say for this example I want to grab the second occurrence of text in between TICKET NBR ($count=2)and done, essentially the output would be

! TICKET NBR : 2 ! GSI : 102 ! 3100.2.112.1 11/06/2013 16:00:45 ! 3100.2.22.3 65 ! 3100.2.134.2 3 !

Well, you could always use:-

grep "TICKET NBR" input_filename | head -2 | tail -1

What further processing are you considering. That may vary the responses you get.

I hope that this helps,

Robin
Liverpool/Blackburn
UK

please give any thing except this , already tried this and i dont know why i got this error , there is nothing related to connection i'm already working on the same server , its working fine many times but suddenly i got this error

grep: writing output: Connection reset by peer

i need to try this in another way may be SED or AWK

Then try this:

awk '/TICKET NBR/ && ++i==2' file
1 Like

Hi ,

its working fine but sorry im newbe in AWK , please how to make it read from count ,
i'm already have acounter lets say

nbrTickets =100
while [ $count -le $nbrTickets ]
do
awk '/TICKET NBR/{Here put count print}' file > $tkt

What do you want to achieve? Get the first 100 occurrences of 'TICKET NBR'?

the script is working fine , i just want to get one by one , for example get the first one and do some editing then get the second one and so on
how to put this in a loop

I don't completely understand your goal, but if you want to parse the count variable to awk you can do this:

awk '/TICKET NBR/ && ++i==c' c=$count file
1 Like

What shell are you working in. There are differences for creating a loop in sh, csh, ksh, bsh, bash, .........

Robin