Split String with a Delimiter in Shell Script

You can use Internal Field Separator (IFS) variable in shell script to split string into array. When we set IFS variable then the assignment to IFS only takes place to that single command’s environment to read. It then parses the input according to the IFS variable value into an array that we can iterate over all values. This is a most preferred way to split string if source string has spaces.

IFS: Internal field separator (abbreviated IFS) refers to a variable which defines the character or characters used to separate a pattern into tokens for some operations.

testscript.sh

#!/bin/bash

STRING="value.one;value-two;value3;value_4;value 5"
IFS=';' read -ra VALUES <<< "$STRING"

## To pritn all values
for i in "${VALUES[@]}"; do
    echo $i
done

Output

sh testscript.sh
value.one
value-two
value3
value_4
value 5

If the source string doesn’t have spaces, then you can use replace all occurrences of the delimiter(‘,’) in the string STRING with ‘ ‘ (a single space), then interprets the space-delimited string as an array.

STRING="value.one,value-two,value3,value_4"
VALUES=(${STRING//,/ })

## To pritn all values
for i in "${VALUES[@]}"; do
    echo $i
done

Output

value.one
value-two
value3
value_4
(Visited 5,802 times, 12 visits today)