How to split one string into multiple variables in bash shell?
To split a string separated by -
, you can use read
with IFS
:
$ IFS=- read -r var1 var2 <<< ABCDE-123456
$ echo "$var1"
ABCDE
$ echo "$var2"
123456
Edit:
Here is how you can read each individual character into array elements:
$ read -ra foo <<<"$(echo "ABCDE-123456" | sed 's/./& /g')"
Dump the array:
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]="-" [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'
If there are spaces in the string:
$ IFS=$'\v' read -ra foo <<<"$(echo "ABCDE 123456" | sed $'s/./&\v/g')"
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]=" " [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'
If you know it's going to be just two fields, you can skip the extra subprocesses like this, using :
var1=${STR%-*}
var2=${STR#*-}
What does this do? ${STR%-*}
deletes the shortest substring of $STR
that matches the pattern -*
starting from the end of the string. ${STR#*-}
does the same, but with the *-
pattern and starting from the beginning of the string. They each have counterparts %%
and ##
which find the longest anchored pattern match. If anyone has a helpful mnemonic to remember which does which, let me know! I always have to try both to remember.
See the bash documentation for more information.