Home > Back-end >  Split string in Array after specific delimited and New line
Split string in Array after specific delimited and New line

Time:10-21

$string="name: Destination Administrator
    description: Manage the destination configurations, certificates and subaccount trust.
    readOnly:
    roleReferences:
    - roleTemplateAppId: destination-xsappname!b62
      roleTemplateName: Destination_Administrator
      name: Destination Administrator"

I have above string each line is delimited by newline char, and I like to create array with two column after "-" as below

Col1                    col2
roleTemplateAppId       destination-xsappname!b62
roleTemplateName        Destination_Administrator
name                    Destination Administrator

I tried below but it is not returning correct array

IFS='- ' read -r -a arrstring <<< "$string"
echo "${arrstring [1]}"

CodePudding user response:

Assumptions:

  • OP is unable to use a yaml parser (per Léa's comment)
  • the input is guaranteed to have \n line endings (within the data)
  • the - only shows up in the one location (as depicted in OP's sample input); otherwise we need a better definition of where to start parsing the data
  • we're interested in parsing everything that follows the -
  • data is to be parsed based on a : delimiter, with the first field serving as the index in an associative array, while the 2nd field will be the value stored in the array
  • leading/trailing spaces to be removed from array indexes and values

One sed idea for pulling out just the lines we're interested in:

$ sed -n '/- /,${s/-//;p}' <<< "${string}"
     roleTemplateAppId: destinationxsappname!b62
      roleTemplateName: Destination_Administrator
      name: Destination Administrator

Adding a few more bits to strip off leading/trailing spaces:

$ sed -n '/- /,${s/-//;s/^[ ]*//;s/[ ]*$//;s/[ ]*:[ ]*/:/;p}' <<< "${string}"                                          
roleTemplateAppId:destination-xsappname!b62
roleTemplateName:Destination_Administrator
name:Destination Administrator

From here we'll feed this to a while loop where we'll populate the associative array

unset      arrstring
declare -A arrstring                   # declare as an associative array

while IFS=':' read -r index value
do
    arrstring["${index}"]="${value}"
done < <(sed -n '/- /,${s/-//;s/^[ ]*//;s/[ ]*$//;s/[ ]*:[ ]*/:/;p}' <<< "${string}")

Leaving us with:

$ typeset -p arrstring
declare -A arrstring=([roleTemplateAppId]="destination-xsappname!b62" [name]="Destination Administrator" [roleTemplateName]="Destination_Administrator" )

$ for i in "${!arrstring[@]}"
do
    echo "$i : ${arrstring[$i]}"
done

roleTemplateAppId : destination-xsappname!b62
name : Destination Administrator
roleTemplateName : Destination_Administrator
  • Related