HowTo: Bash Shell Split String Into Array

You can split a string into an array in bash using the IFS (Internal Field Separator) variable and parameter expansion.

Here is an example of how to split a string into an array:

string="one two three four"
IFS=' ' read -ra arr <<< "$string"
for i in "${arr[@]}"; do
echo "$i"
done

In this example, the IFS variable is set to ' ', which tells bash to use a space as the separator between elements in the string. The read command is used to split the string into elements of the arr array, using -r to prevent backslash escapes from being interpreted and -a to assign the elements to an array. The <<< operator is used to pass the string as input to the read command. The for loop is used to iterate over the elements of the array and print each one.

You can use a different separator by changing the value of IFS. For example, to split a string into an array based on a comma, you could use:

string="one,two,three,four"
IFS=',' read -ra arr <<< "$string"
for i in "${arr[@]}"; do
echo "$i"
done

Note: The read command can split strings into arrays, but it does not automatically preserve leading or trailing whitespace for each element in the array. To preserve whitespace, you can use a different method such as parameter expansion or awk.

(https://tjc.org/)

Leave a Comment