[Code Example] Split a string using bash script

Total
0
Shares

In this article we will provide you bash script code to split a string using a delimiter. You can use this code as it is in your existing projects. Common delimiters are , space _ - $ # etc.

Code Example –

1. split() function

#!/bin/bash

split() {
   IFS=$'\n' read -d "" -ra arr <<< "${1//$2/$'\n'}"
   echo "${arr[@]}"
}

sanitized_string=$(split "apples,oranges,pears,grapes" ",")

echo $sanitized_string

# Output: 
# apples oranges pears grapes

2. If delimiter is _

split "Ironman_Thor_Hulk_Captain America" "_"

# Output
# Ironman Thor Hulk Captain America

3. If delimiter is $ – You will need to escape \$

split "Elon\$Jeff\$Bill\$Ambani\$Mark" "$"

# Output: 
# Elon Jeff Bill Ambani Mark

4. To print items in separate lines

#!/bin/bash

nl_split() {
   IFS=$'\n' read -d "" -ra arr <<< "${1//$2/$'\n'}"
   printf '%s\n' "${arr[@]}"
}

nl_split "All words will print in separate lines" " "

# Output -
# All
# words
# will
# print
# in
# separate
# lines

Inspired from Dylan Araps

Live Demo

Demo might not work in private window (incognito)

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like