How do we convert a string into N character array and back to string with spaces? And how do we remove the spaces?
e.g. 123456789 into 2's should give 12 34 56 78 9
Sounds like you don't need the array at all and your final goal is just to insert spaces between groups of two characters. If that's the case you can use
sed 's/../& /g' <<< "your string here"
This will transform your example input 123456789 into the expected output 12 34 56 78 9.
Of course you can assign the result to a variable as usual:
yourVariable="$(sed 's/../& /g' <<< "your string here")"
if needed, how do we remove the spaces?
I'm not sure which spaces you mean. If you are talking about the final result, wouldn't it be easier to use the original input instead of procession the ouput again?
Anyways, you can remove all spaces from a any string using tr -d ' ' <<< "your string" or the parameter substitution ${yourVariable// /}.
$ str='123456789'
$ arr=( $(printf '%s\n' "$str" | sed 's/../& /g') )
$ declare -p arr
declare -a arr=([0]="12" [1]="34" [2]="56" [3]="78" [4]="9")
$ str="${arr[*]}"
$ echo "$str"
12 34 56 78 9
$ str="${str// }"
$ echo "$str"
123456789
$ str=$(printf "%s" "${arr[@]}")
$ echo "$str"
123456789
This would be demonstrative to your question.
Convert a string into N character array:
string="0123456789abcdefghijklmnopqrstuvwxyz"
number_max_of_char_per_set=4
increment_by=$number_max_of_char_per_set
for i in `seq 0 $increment_by ${#string}`
#for i in $(seq 0 ${#string})
do array[$i]=${string:$i:number_max_of_char_per_set}
done
... back to string with spaces:
string_new=${array[@]}
echo "zero element of array is [${array[0]}]"
echo "entire array is [${array[@]}]"
echo $string_new
remove the spaces:
string_new=${string_new//[[:space:]]/}
echo $string_new