Home > Blockchain >  Split variable having comma seprated value into two random part in bash shell
Split variable having comma seprated value into two random part in bash shell

Time:10-19

I have string="1,2,3,4,5,6,7,8" I want to split string in 2 different variable with unique values as below string_p1="1,2,3,4,5" string_p2="6,7,8"

Here i dont want any specific defined logic while splitting variable any random splitting is okay. but i need to ensure that i am not missing any number present in variable string

Please suggest bash script to get the above results ?

CodePudding user response:

I tried with this:

string="1,2,3,4,5,6,7,8"

echo ${string:0:${#string}/2}
echo ${string:${#string}/2}

and it splits the string in half, this is the output:

1,2,3,4
,5,6,7,8

CodePudding user response:

One idea using an array and some basic bash string manipulation:

string='1,2,3,4,5,6,7,8'
IFS=, arr=( ${string} )                 # break on comma delimiter, store in array

Result:

$ typeset -p arr
declare -a arr=([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="6" [6]="7" [7]="8")

$ len="${#arr[@]}"
8

To generate a random number between 0 and 8 (length of arr[]), eg:

$ n=$(( RANDOM % len ))
$ echo $n
2                                       # obviously this will vary between 0 and 8 based on value of $RANDOM

Build our final strings:

$ string_p1=${arr[@]:0:n}
$ string_p2=${arr[@]:n}
$ typeset -p string_p1 string_p2
declare -- string_p1="1 2"
declare -- string_p2="3 4 5 6 7 8"

Now replace spaces with commas:

$ string_p1="${string_p1// /,}"
$ string_p2="${string_p2// /,}"
$ typeset -p string_p1 string_p2
declare -- string_p1="1,2"
declare -- string_p2="3,4,5,6,7,8"

NOTE: because the split is based solely on $RANDOM there is a good chance one of the resulting strings can be empty (eg, n=0); OP can add more logic to address this issue as needed (eg, if n=0 then set n=1 to ensure string_p1 is not empty)


Taking for a spin with a different input:

string='3,24,666.83,2,9,0,34,23,45,12,1'
IFS=, arr=( ${string} )
len="${#arr[@]}"
n=$(( RANDOM % len ))
string_p1=${arr[@]:0:n}
string_p2=${arr[@]:n}
string_p1="${string_p1// /,}"
string_p2="${string_p2// /,}"
typeset -p len n string_p1 string_p2

This generates:

declare -- len="11"
declare -- n="8"
declare -- string_p1="3,24,666.83,2,9,0,34,23"
declare -- string_p2="45,12,1"
  • Related