NoRestartOnUpdate
NoRestartOnUpdate

Reputation: 79

KSH Split String Issues

I have a string in a variable Var. And the value looks like this:

Var="Key1:Val1~Key2:Val2~"

I just simply need this split by "~" and assigned to an array in KSH only

When I try Var2=$(echo $Var | sed $'s/~/\\n/g')

and check the size of Var2 array as follows: ArrSize=${#Var2[@]}

I always get 1. I would have imagined that would be 2. Please Help

Upvotes: 0

Views: 59

Answers (1)

markp-fuso
markp-fuso

Reputation: 34244

Assuming you want to use the x=( list of array items ) method of populating the array then you need to wrap the right side of the assignment in a pair of parens, eg:

$ Var2=( $( echo $Var | sed $'s/~/\\n/g' ) )

$ typeset -p Var2
typeset -a Var2=(Key1:Val1 Key2:Val2)

$ echo "${#Var2[@]}"
2

Other options that accomplish the same thing but reduce the overhead of subprocess calls:

here string:

$ Var2=( $(sed 's/~/ /g' <<< "${Var}") )

$ typeset -p Var2
typeset -a Var2=(Key1:Val1 Key2:Val2)

$ echo "${#Var2[@]}"
2

parameter substitution:

$ Var2=( ${Var//\~/ } )

$ typeset -p Var2
typeset -a Var2=(Key1:Val1 Key2:Val2)

$ echo "${#Var2[@]}"
2

NOTE: while ${var//~/ } works in ksh, other shells (eg, bash) require the ~ to be escaped (ie, \~); ksh appears to work with both - ~ and \~ = so I've updated the answer to include the escape

Upvotes: 2

Related Questions