Here’s my situation. Currently, I have a script that accepts two arguments: book name and chapter name. For example:
$ myscript book1 chap1
Now, for reasons that would take a long time to explain, I would prefer my script to be able to take a single argument of the following format: {book name}.{chapter name}. For example:
$ myscript book1.chap1
The difficulty for me is that I do not know how to take a string $1=abc.xyz and turn it into two separate variables, $var1=abc and $var2=xyz. How can I do this?
If it’s just two tags you can use a bash expression
It’s faster than
cutbecause it’s a shell builtin. Note that this puts everything before thefirstlast dot intobeforedotand everything after intoafterdot.EDIT:
There’s also a substitution/reinterpretation construct if you want to split by an arbitrary number of tokens:
You’re replacing dots by spaces and then that gets interpreted as an array declaration+definition because of the parentheses around it.
However I’ve found this to be less portable to bash’ siblings and offspring. For example, it doesn’t work in my favourite shell,
zsh.Arrays need to be dereferenced with braces and are indexed from 0:
You can loop through them as well by dereferencing the whole array with [@]: