Bash: Split One String Into Multiple Variables

Split “abc-123” into two variables by -

var="abc-123"

Using awk

var1=$(echo $var | awk -F- '{print $1}')
var2=$(echo $var | awk -F- '{print $2}')

Using cut

var1=$(echo $var | cut -f1 -d-)
var2=$(echo $var | cut -f2 -d-)

Using IFS and read

IFS=- read var1 var2 <<< $var

Using Shell Parameter Expansion/Substitution

See:

${var%Pattern} Remove from $var the shortest part of Pattern that matches the back end (right) of $var.

${var%%Pattern} Remove from $var the longest part of Pattern that matches the back end (right) of $var.

${var#Pattern} Remove from $var the shortest part of $Pattern that matches the front end (left) of $var.

${var##Pattern} Remove from $var the longest part of $Pattern that matches the front end (left) of $var.

var1=${var%-*}
var2=${var#*-}

Leave a Comment

Your email address will not be published. Required fields are marked *