Issue
How can ı convert a string to an array in shell script?
For example i want to put "apple" to an array.
array[0] = a
array[1]=p
array[2]=p
array[3]=l
array[4]=e
I tried a lot of things but none of them worked. I tried to use IFS but i have no space or comma in my word so it didn't work.
Solution
Parameter expansion is relevant here: ${#var}
gives you the number of characters in var
, and ${var:start:len}
takes len
characters from var
, starting at position start
.
Combine those two techniques and you get:
#!/usr/bin/env bash
string='apple'
array=( )
for ((i=0; i<${#string}; i++)); do
array[$i]=${string:i:1}
done
declare -p array
...which emits as output:
declare -a array=([0]="a" [1]="p" [2]="p" [3]="l" [4]="e")
Answered By - Charles Duffy Answer Checked By - Dawn Plyler (WPSolving Volunteer)