by Sai gowtham

How to split a string in bash by delimiter

We can do this by setting an internal file separator (IFS) variable to delimiter ; then parse it as an array and use for loop to get the each string.

In this below example, we are splitting a dummy variable string by semicolon ;.

dummy="king;ring;ping"

# turns string to array
IFS= ";" read -ra ADDR <<< "$dummy"

# for loop
for i in "${ADDR[@]}"; do
    echo $i
done

Output:

king
ring
ping

Split string by comma

dummy="king,ring,ping"

# turns string to array
IFS= "," read -ra ADDR <<< "$dummy"

# for loop
for i in "${ADDR[@]}"; do
    echo $i
done

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course