user245011
user245011

Reputation: 75

In Bash How to remove substring matching from back of the string

version=0.1.2-2-gb12431b-3.4.5

What is the best utility in bash to remove the substring starting from hyphen from back of the string(-3.4.5).

I want the new_version=0.1.2-2-gb12431b, with the substring removed. Any suggestion on what is the right way to do it.

Upvotes: 0

Views: 54

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295825

Parameter Expansion (prior link is to relevant man page section):

new_version=${version%-*}

Because this is only a single %, the expression is evaluated as non-greedy, so it stops at the first dash.

Using a parameter expansion avoids any call out to external tools -- cut, awk, sed, etc -- and is thus far more efficient.


See also:

Upvotes: 5

Related Questions