How do I split a string on a delimiter in Bash?

 

In Bash, you can split a string on a delimiter using the IFS (Internal Field Separator) variable and the read command. Here's how to do it with an example:

bash
# Define the input string input_string="apple,banana,cherry,date" # Set the delimiter delimiter="," # Create an array to store the split values IFS="$delimiter" read -ra split_array <<< "$input_string" # Loop through the array to access the split values for value in "${split_array[@]}"; do echo "Split value: $value" done

In this example:

  1. We define the input string input_string containing comma-separated values.

  2. We set the delimiter variable to , to specify that we want to split the string at commas.

  3. We use the IFS (Internal Field Separator) variable to temporarily change the field separator to our specified delimiter.

  4. We use the read command with the -ra options to read the input string and split it into an array called split_array.

  5. Finally, we loop through the split_array to access and print each split value.

When you run this script, it will split the input_string on the comma delimiter and print each split value:

mathematica
Split value: apple Split value: banana Split value: cherry Split value: date

This method allows you to split a string into an array of values based on a specified delimiter in Bash. You can change the delimiter variable to split the string using a different character or sequence of characters.

Comments