bash script help splitting string



  • I have some old code that I need to update.

    # initializing agi variables
    declare -a array
    while read -e ARG && [ "$ARG" ] ; do
     array=(` echo $ARG | sed -e 's/://'`)
     export ${array[0]}=${array[1]}
    done
    

    The source data looks like this.

    Begin Argument dump:
     agi_request: testalert.agi
     agi_channel: PJSIP/103-00000b10
     agi_language: en
     agi_type: PJSIP
     agi_uniqueid: 1593012912.5212
     agi_version: 17.3.0
     agi_callerid: 16365551212
     agi_calleridname: Bundy Assoc Inc
     agi_callingpres: 0
     agi_callingani2: 0
     agi_callington: 0
     agi_callingtns: 0
     agi_dnid: 6605551212
     agi_rdnis: unknown
     agi_context: macro-dialout-trunk
     agi_extension: continue
     agi_priority: 2
     agi_enhanced: 0.0
     agi_accountcode: JB103
     agi_threadid: 140422957213440
    

    The problem is the Caller ID Name has spaces which get automatically split into further array elements.

    I was thinking to use IFS, but then I thought we recently had a thread with a different method that was better, but I cannot find that... My google failed me this morning.



  • try this:

    # initializing agi variables
    declare -a array
    while read -e ARG && [ "$ARG" ] ; do
     array=(` echo "$ARG" | sed -e 's/://'`)
     export ${array[0]}=${array[@]:1}
    #next added line for debug only. comment this out in prod.
     echo "${array[0]}=${array[@]:1}"
    done
    

    if you want to "slice" an array use the syntax: ${array[@]:from:to}, not providing the 'to' arg means go up to the end of array.
    source here.



  • @matteo-nunziati said in bash script help splitting string:

    try this:

    # initializing agi variables
    declare -a array
    while read -e ARG && [ "$ARG" ] ; do
     array=(` echo "$ARG" | sed -e 's/://'`)
     export ${array[0]}=${array[@]:1}
    #next added line for debug only. comment this out in prod.
     echo "${array[0]}=${array[@]:1}"
    done
    

    if you want to "slice" an array use the syntax: ${array[@]:from:to}, not providing the 'to' arg means go up to the end of array.
    source here.

    Almost right. Because of the export command parsing spaces, I needed to stick it in a variable first.

    # Variable to hold the details for the log file
    DUMPARG=" Begin Argument dump:\n"
    # Create an Array to hold the results of the loop
    declare -a array
    # Loop through the AGI variables
    while read -e ARG && [ "$ARG" ] ; do
     # Dump them into an array, after removing the :
     array=(` echo $ARG | sed -e 's/://'`)
     # take the array and create a variable from the first element put the rest as the value
     # value must be put into a holding variable to parse correctly by the export command
     val=${array[@]:1}
     export ${array[0]}="$val"
     # Dump them into a string for the log file
     DUMPARG="$DUMPARG $ARG\n"
    done