This question already has an answer here:
I've been looking for a solution and found similar questions, only they were attempting to split sentences with spaces between them, and the answers do not work for my situation.
Currently a variable is being set to something a string like this:
ABCDE-123456
and I would like to split that into 2 variables, while eliminating the "-". i.e.:
var1=ABCDE
var2=123456
How is it possible to accomplish this?
This is the solution that worked for me:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
Is it possible to use the cut command that will work without a delimiter (each character gets set as a variable)?
var1=$(echo $STR | cut -f1 -d?)
var2=$(echo $STR | cut -f1 -d?)
var3=$(echo $STR | cut -f1 -d?)
etc.
If you know it's going to be just two fields, you can skip the extra subprocesses like this:
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.read
withIFS
are perfect for this:Edit:
Here is how you can read each individual character into array elements:
Dump the array:
If there are spaces in the string:
Using bash regex capabilities:
OUTPUT
Sounds like a job for
set
with a customIFS
.(You will want to do this in a function with a
local IFS
so you don't mess up other parts of your script where you requireIFS
to be what you expect.)If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
I chose
cut
here because you could simply extend the code for a few more variables...