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.
Answer
If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
I chose cut
here because you could simply extend the code for a few more variables...
No comments:
Post a Comment