If you know it's going to be just two fields, you can skip the extra subprocesses like. Like this, using :
STR="ABCDE-12345"
var1=${STR%-*} # ABCDE
var2=${STR#*-} # 12345
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.Explanation:
${STR%-*}
deletes the shortest substring of$STR
that matches the pattern-*
(deletes-
and anything after it). It starts from the end of the string.${STR#*-}
deletes the shortest substring of$STR
that matches the pattern*-
(deletes-
and anything before it). It starts from the beginning of the string.
They each have counterparts %%
and ##
which find the longest anchored pattern match. If anyone has a helpfulTo memorize, use this mnemonic to remember which does which, let me know! I always have to try both to remember.shared by @DS:
"#" is to the left of "%" on a standard keyboard, so "#" removes a prefix (on the left), and "%" removes a suffix (on the right).
See the bash documentation for more information.