How to Use sed to Split String Based on Delimiter


Often you may want to use sed to split a string based on a specific delimiter.

You can use the following basic syntax to do so:

echo $my_string | sed 's/_/\n/g'

This particular example will split the string variable named $my_string based on where any underscores occur in the string.

Here is what the various sed commands do:

  • s/: Used to replace a specific pattern with another pattern
  • _: Used to specify that an underscore should be used as delimiter
  • \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 use this syntax in practice.

Example: How to Use sed to Split String Based on Delimiter

Suppose we define a string variable named teams that contains the names of various basketball teams separated by underscores.

We can use the following syntax to split the string variable based on where any underscore occurs:

teams="Mavs_Nets_Hawks_Kings_Lakers_Cavs_Pacers"

echo $teams | sed 's/_/\n/g' 

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

sed split string based on delimiter

Notice that the string has been split based on where any underscore occurs.

Feel free to replace the underscore with a different delimiter to instead split the string based on a different delimiter.

Related Tutorials

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

How to Use sed to Replace All Text After Match
How to Use sed to Replace All Text Before Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply