Bash – How to Split a String by a Separator

bashtext processing

I would like to split a string into substrings, separated by some separator (which is also a string itself).

How can I do that

  • using bash only? (for minimalism, and my main interest)

  • or If allowing some text processing program? (for convenience when the program is available)

Thanks.

Simple example,

  • split 1--123--23 by -- into 1, 123 and 23.
  • split 1?*123 by ?* into 1 and 123

Best Answer

Pure bash solution, using IFS and read. Note that the strings shouldn't contain $'\2' (or whatever else you use for IFS, unfortunately $'\0' doesn't work, but e.g. $'\666' does):

#!/bin/bash

split_by () {
    string=$1
    separator=$2

    tmp=${string//"$separator"/$'\2'}
    IFS=$'\2' read -a arr <<< "$tmp"
    for substr in "${arr[@]}" ; do
        echo "<$substr>"
    done
    echo
}


split_by '1--123--23' '--'
split_by '1?*123' '?*'

Or use Perl:

perl -E 'say for split quotemeta shift, shift' -- "$separator" "$string"
Related Question