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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap