How to Split a String based on Delimiter in Bash Scripting

In Bash scripting, we can split a string into substrings based on a delimiter using the built-in IFS - Internal Field Separator variable and the read command.

Let's take a look at an example.

Example 1:

    #!/bin/bash
    
    data_string="1,2,3,4,5,6,7,8,9,10"
    
    delimiter=","
    
    IFS="$delimiter"
    
    read -ra str_array <<< "$data_string"
    
    for element in "${str_array[@]}"; do
        echo "$element"
    done
Split a String into SubString Bash Script Example

Example 2: Delimiter as Pipe

    #!/bin/bash
    
    data_string="USA|UK|China|Japan|India|France"
    
    IFS="|"
    
    read -ra str_array <<< "$data_string"
    
    for element in "${str_array[@]}"; do
        echo "$element"
    done

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!