Bash: How to Split a String Using Multiple Delimiters


You can use the following basic syntax in Bash to split a string based on multiple potential delimiters:

echo $my_string | sed 's/[,;|]/\n/g'

This particular example will split the string variable named $my_string based on where any of the following delimiters occur:

  • ,
  • ;
  • |

Here is what the various sed commands do:

  • s/: Used to replace a specific pattern with another pattern
  • [ ]: Used to specify the values to replace
  • \n: Used to specify that newlines should be used as replacements
  • \g: Used to specify that the replacements should be made “globally”, i.e. for each occurrence of the pattern

The following example shows how to split a string based on multiple delimiters in practice.

Example: How to Split a String Using Multiple Delimiters in Bash

Suppose we define a string variable named teams in Bash that contains the names of various basketball teams separated by several different delimiters.

We can use the following syntax to split the string variable based on where any of the following delimiters occur:

  • ,
  • ;
  • |
teams="Mavs,Nets,Hawks;Kings|Lakers,Cavs"

echo $teams | sed 's/[,;|]/\n/g' 

The following screenshot shows how to use this syntax in practice:

Bash split string on multiple delimiters

Notice that the string has been split based on where any of the three delimiters occurred.

Note that we included three delimiters within the brackets [ ] in this example but you can include as many delimiters as you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Extract First Number from a String
Bash: How to Count Number of Words in String
Bash: How to Count Number of Characters in String
Bash: How to Check if String Starts with Specific Value

Leave a Reply