Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split string on last "-" in bash?

Tags:

bash

split

Given the string "foo-bar-1.4.5" or "for-bar-baz-1.8.3" how can I break these strings into 2 parts: first part everything before the last "-" ("foo-bar", "foo-bar-baz") and the last part ("1.4.5" and "1.8.3") respectively?

I can imagine a few strategies, like splitting on "-" then adding everything but the last part back together. Or maybe a regex with substitution. Bash is the biggest thing in my way though. I'm not sure what the syntax would look like and I've tried a few things with sed and awk but my lack of comfort with bash arrays is hanging me up. I figure one of you bash experts can bang this out in short order and teach me via an example pretty fast.

EDIT: I won't know the number of "-" before the command is run. The method should handle n >= 1 of "-".

like image 550
Dane O'Connor Avatar asked Mar 11 '26 09:03

Dane O'Connor


1 Answers

You can use parameter expansion for this:

${var#pattern} removes the shortest matching pattern from the beginning of var. Using ## removes the longest matching pattern. % and %% work similarly, but remove from the end of var.

#!/bin/bash
first="foo-bar-1.4.5"
second="foo-bar-baz-1.8.3"

echo ${first%-*}
echo ${first##*-}

echo ${second%-*}
echo ${second##*-}

Output:

foo-bar
1.4.5
foo-bar-baz
1.8.3
like image 155
Josh Jolly Avatar answered Mar 14 '26 02:03

Josh Jolly