Bash Split String

Bash Split String

Bash Split String – In this Bash Tutorial, we shall learn how to split a string in bash scripting.

  1. Split string with single character delimiter using IFS (Internal Field Separator).
  2. Split string with multiple character delimiter using Parameter Expansions.

 

Split String with single character delimiter(s) in Bash using IFS

To split a string in bash using IFS, follow the below steps :

  1. Set IFS to the delimiter you would want.
    IFS='<delimiter>' IFS is an internal variable that determines how Bash recognizes word boundaries. The default value of IFS is white space. If you set it to some other value, reset it to default whitespace.
  2. Read your string to a variable with options -ra.
    read -ra ARR <<< "$str"
    OptionDescription
    -rBackslash does not act as escape character.
    -a ARRThe words(separated by IFS) are assigned to sequential index of array ARR beginning at zero.

    Now you have your string split by the delimiter (set in IFS) stored in array ARR.

  3. You may now access the tokens split into array using a bash for loop.

Examples :

Following are the examples to demonstrate the splitting of string in bash scripting

Example 1 : Space as delimiter

Run the above bash shell script in terminal
 

Example 2 : Symbol as delimiter

Run the above bash shell script in terminal
 

Split String with multiple character delimiter

To split a string with a multiple character delimiter, following are two of the many possible ways, one with idiomatic and the other with just basic if and while loop :

Example : With idiomatic expressions

Following is an example with idiomatic expressions, and thus a very compact script.

Bash Script file

Following parameter expansions are used (Reference : Bash Man Page)

ExpansionDescription
${parameter%%word}Remove longest matching suffix pattern.
${parameter#word}Remove shortest matching prefix pattern.

 

Example : Without any idiomatic expressions

Bash Script File