Bash Split String

Bash Split String

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

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

  1. Set IFS (Internal Field Separator) 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