Splitting a string into two variables

Even though the command-line is like my second home, I still fall short in terms
of being able to some basic things. This is primarily because they just don’t
come up that often so when I do figure out how to do it, I just don’t retain
what I’ve learned.

Most of these one-off tasks that end up falling out of my memory are related to
string manipulation. While I’m getting better with things like sed, there is a
lot I don’t know, especially in terms of how powerful string manipulation is in
shell scripting.

Recently, while optimizing one of my scripts that powers my VPS Showdown
posts, I wanted to take a string, split it by the colon : character and assign
it to multiple variables that could be referenced.

If this were Node.js or JavaScript, I’d simply .split() and destructure the
array into variables or reference the array items, no big deal.

After doing some research, if you want to split a string into 2 parts, you can
use the following string manipulators:

STRING="one:two"

# To grab the first part (outputs 'one')
echo "${STRING%:*}"

# To grab the second part (outputs 'two')
echo "${STRING#*:}"

And if you must assign the parts to variables, you can do that as well:

ONE="${STRING%:*}"
TWO="${STRING#*:}"

This is all well and good, but falls apart quick if your string has more than
one delimited character, in this case, the colon :.

Since I didn’t need to split on more than one delimiter, I won’t be delving into
how to split on multiple delimiters since it requires a bit more code and there
are some subtle nuances between doing so in Z shell and Bash.

Will save that for another post in the future!

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.