RDX
RDX

Reputation: 155

How to extract certain strings based on previous lines in tcl

Suppose I have the following string:

m=audio 56000 RTP/AVP 0 8 18 205 150 101
o=India-SIPUA 2331 0 IN IP4 10.77.34.6
s=SIP Call
m=audio 22058 RTP/AVP 0 8 18 105 104 101
c=IN IP4 10.77.34.6

Now I need to search the second "m=audio" based on the searching of the string "o=India-SIPUA 2331 0 IN IP4 10.77.34.6"

For this I have got the following code to search the string "o=India-SIPUA 2331 0 IN IP4 10.77.34.6"

set buffer "m=audio 56000 RTP/AVP 0 8 18 205 150 101
o=India-SIPUA 2331 0 IN IP4 10.77.34.6
s=SIP Call
m=audio 22058 RTP/AVP 0 8 18 105 104 101
c=IN IP4 10.77.34.6"
set patt "India-SIPUA"
set ipaddress "10.77.34.6"

foreach buf [split $buffer "\n"] {
  if {[regexp "o=$patt.*$ipaddress" $buf match]} {
     puts "+++++++Port==$match++++++"
     break
  } else {
     puts "\n Not found"
  }
}

Now what should I write in order to get the m=audio string which comes just after the string "o=India-SIPUA..."

Upvotes: 1

Views: 368

Answers (2)

Tensibai
Tensibai

Reputation: 15784

You can achieve that on one pass like this:

#!/usr/bin/tclsh
set buffer "m=audio 56000 RTP/AVP 0 8 18 205 150 101
o=India-SIPUA 2331 0 IN IP4 10.77.34.6
s=SIP Call
m=audio 22058 RTP/AVP 0 8 18 105 104 101
c=IN IP4 10.77.34.6"
set patt "India-SIPUA"
set ipaddress "10.77.34.6"

if {[regexp "(o=$patt.+$ipaddress)\n(?:.*\n)*(m=audio .*)\n.*" $buffer match match1 match2]} {
     puts "+++++++Port==$match1++++++"
     puts "+++++++Audio==$match2+++++"
}

for the regex itself: (o=$patt.+$ipaddress)\n(?:.*\n)*(m=audio .*)\n.*

  • (o=$patt.+$ipaddress)\n First capture group () matching the o=...[your pattern] until a \n (not captured)
  • (?:.*\n)* non capturing group of text with newline at end, with * operator match this group none or many times
  • (m=audio .*)\n Second capture group () matching the m=audio line until \n (not capturing it)
  • .* Just to match the rest of buffer, not capturing it.

For the vars in regexp, first is an rray of matches, the others are destination for the capture groups.

If the buffer match, print the two captured groups with prefixs.

Output:

 ./script.tcl
+++++++Port==o=India-SIPUA 2331 0 IN IP4 10.77.34.6++++++
+++++++Audio==m=audio 22058 RTP/AVP 0 8 18 105 104 101+++++

Upvotes: 1

migfilg
migfilg

Reputation: 542

Use a flag to know whether you have found the 1st pattern, in the then test the flag and either change the contents of patt to the regexp you need to match next, change the flag and continue the loop, or the 2nd pattern was found and you break the loop.

Upvotes: 1

Related Questions