Andrea Visnenza Andy Andrea Visnenza Andy - 1 month ago 9
Linux Question

linux bash cut one row which starts with a certain string

Good day,

im using linux bash commands to extract certain data of each sip account and put them next to each other.

i have an array called $peers that i put all 1000 sips into and now i need to for loop through them to set every sip to its useragent.

what i have so far is

#! /bin/bash

peers="$(asterisk -rx "sip show peers" | cut -f1 -d" " | cut -f1 -d"/" "=")" "= " asterisk -rx "sip show peer " $peer | cut -f2 -d"Useragent"

for peer in $peers do
echo $peers
done

#echo $peers


I need to extract a row from a collection of rows that starts with "Useragent"

I start by running
asterisk -rx "sip show peer 101"
and that gives me the result below

* Name : 101
Description :
Secret : <Set>
MD5Secret : <Not set>
Remote Secret: <Not set>
Context : outgoing
Record On feature : automon
Record Off feature : automon
Subscr.Cont. : <Not set>
Language :
Tonezone : <Not set>
AMA flags : Unknown
Transfer mode: open
CallingPres : Presentation Allowed, Not Screened
Callgroup :
Pickupgroup :
Named Callgr :
Nam. Pickupgr:
MOH Suggest :
Mailbox :
VM Extension : asterisk
LastMsgsSent : 0/0
Call limit : 0
Max forwards : 0
Dynamic : Yes
Callerid : "" <>
MaxCallBR : 384 kbps
Expire : 23
Insecure : no
Force rport : Yes
Symmetric RTP: Yes
ACL : No
DirectMedACL : No
T.38 support : No
T.38 EC mode : Unknown
T.38 MaxDtgrm: -1
DirectMedia : Yes
PromiscRedir : No
User=Phone : No
Video Support: No
Text Support : No
Ign SDP ver : No
Trust RPID : No
Send RPID : No
Subscriptions: Yes
Overlap dial : Yes
DTMFmode : rfc2833
Timer T1 : 500
Timer B : 32000
ToHost :
Addr->IP : xxx.xxx.xxx.xxx:5060
Defaddr->IP : (null)
Prim.Transp. : UDP
Allowed.Trsp : UDP
Def. Username: 101
SIP Options : (none)
Codecs : (gsm|ulaw|alaw|g729|g722)
Codec Order : (gsm:20,g722:20,g729:20,ulaw:20,alaw:20)
Auto-Framing : No
Status : OK (9 ms)
Useragent : UniFi VoIP Phone 4.6.6.489
Reg. Contact : sip:101@xxx.xxx.xxx.xxx:5060;ob
Qualify Freq : 60000 ms
Keepalive : 0 ms
Sess-Timers : Accept
Sess-Refresh : uas
Sess-Expires : 1800 secs
Min-Sess : 90 secs
RTP Engine : asterisk
Parkinglot :
Use Reason : No
Encryption : No


Now i need to cut this part
Useragent : UniFi VoIP Phone 4.6.6.489


and display it as
101 : UniFi VoIP Phone 4.6.6.489


any help would be much appreciated

Thank you. that top answer worked perfectly. this is my solution now.

peer="$(asterisk -rx "sip show peers" | cut -f1 -d" " | cut -f1 -d"/" )"


for peer in $peers do

output= "$(asterisk -rx "sip show peer $peers" | sed -nE '/Useragent/ s/^[^:]+/101 /p')"
echo $output


done


But is is still giving issue, my problem is the loop of the variables

Answer

With sed:

... | sed -nE '/Useragent/ s/^[^:]+/101 /p'
  • /Useragent/ matches line(s) with Useragent it

  • s/^[^:]+/101 substitutes the portion from start till : (exclusive) with 101