Splitting a String in Bash on the FIRST Occurrence of a Character

About a year ago I posted an article about how to split into an array of values based on a given delimiter in bash.

The following is how to take that same string and split it on the first occurrence of the same user defined delimiter.

Both use the ‘read’ command, but in a slightly different way.

Instead of passing read the -a [aname] parameter which tells it that “The words are assigned to sequential indices of the array variable aname, starting at 0.”, we pass is -r which indicates that “Backslash does not act as an escape character.  The backslash is considered to be part of the line.”.  This will make sure to include any backslash that is in the string in your output.

Then, we provide two variables into which we will store the split string.

#!/bin/bash

SOURCE_STRING='foo|blah|moo'

# Save the initial Interal Field Separator
OIFS="$IFS"

# Set the IFS to a custom delimiter
IFS='|'

read -r KEY VALUE <<< "${SOURCE_STRING}"
echo "KEY = $KEY, VALUE = $VALUE"

# Reset original IFS
IFS="$OIFS"

Leave a Reply