Removing all text except text between 2 matching pattern Shell Script

Viewed 95

Let me explain what I am trying to do . I am trying to extract a key between 2 matching patterns and delete everything from a command output (not a file) and take it into a variable for further use .

asterisk -r -x "sip show peer 2030" output the following text

-------truncated and given dummy keys ----- 
  Prim.Transp. : UDP
  Allowed.Trsp : UDP,TCP
  Def. Username: 2030
  SIP Options  : (none)
  Codecs       : (ulaw|alaw|g729)
  Auto-Framing : No
  Status       : OK (650 ms)


Useragent    : LinphonephoneiOS/1.0 (Linphone’s iPhone) LinphoneSDK/4.4.0 Reg. Contact : sip:2030@192.168.10.246:57109;pn-provider=apns.dev;pn-prid=9D0C98263E98EE1E282516D585C298BA3915398117C4C30CD3FD352BEEBB7581:remote&2CA57031CAA11360A09B9F37A13DE83CB337BF860352FSAFD7E9B444E5DB673B:voip;pn-param=ABCD1234.org.linphone.linphone.remote&voip;pn-msg-str=IM_MSG;pn-call-str=IC_MSG;pn-groupchat-str=GC_MSG;pn-call-snd=notes_of_the_optimistic.caf;pn-msg-snd=msg.caf;pn-timeout=0;pn-silent=1;transport=udp
  Qualify Freq : 60000 ms
  Keepalive    : 0 ms
  Variables    :
  DEVICENAME = 2030
  Sess-Timers  : Accept
  Sess-Refresh : uas
  Sess-Expires : 1800 secs
  Min-Sess     : 90 secs
  RTP Engine   : asterisk
  Parkinglot   : parking-1
  Use Reason   : No
  Encryption   : No
  RTCP Mux     : No
---------truncated and given dummy keys ---------------

I am interested in only the key(2CA57031CAA11360A09B9F37A13DE83CB337BF860352FSAFD7E9B444E5DB673B)between remote&. and :voip; I would like to delete everything from the command out except the key and store it in variable for further processing.

I tried below but failed.

US="2030"
d=($(asterisk -r -x "sip show peer $US" | sed -e "s/.*:remote&\(.*\):voip.*/\1/"))
echo $d
2 Answers

You are sooo clooossee! (so close) You simply need to suppress the normal printing of output from sed and print only if a substitution is made, e.g.

d=($(asterisk -r -x "sip show peer $US" | sed -n "s/.*:remote&\(.*\):voip.*/\1/p"))

Where -n suppresses the normal printing of pattern space (you don't need -e with a single expression) and the /p at the end provides the print only on substitution.

note: unless you want d as an indexed array with a single-string as its only element, just use d=$(...)

With awk could you please try following.

d=($(asterisk -r -x "sip show peer $US" | awk 'match($0,/:remote&.*:voip/){print substr($0,RSTART+6,RLENGTH-11)}'))

For more clarity of above command mentioning only awk command as follows:

awk 'match($0,/:remote&.*:voip/){print substr($0,RSTART+6,RLENGTH-11)}'
Related