tatsu
tatsu

Reputation: 2536

bash shell reworking variable replace dots by underscore

I can't see to get it working :

echo $VERSIONNUMBER

i get : v0.9.3-beta

VERSIONNUMBERNAME=${VERSIONNUMBER:1}
echo $VERSIONNUMBERNAME

I get : 0.9.3-beta

VERSION=${VERSIONNUMBERNAME/./_}
echo $VERSION

I get : 0_9.3-beta

I want to have : 0_9_3-beta

I've been googling my brains out I can't make heads or tails of it.

Ideally I'd like to remove the v and replace the periods with underscores in one line.

Upvotes: 10

Views: 8737

Answers (2)

John1024
John1024

Reputation: 113934

Let's create your variables:

$ VERSIONNUMBER=v0.9.3-beta
$ VERSIONNUMBERNAME=${VERSIONNUMBER:1}

This form only replaces the first occurrence of .:

$ echo "${VERSIONNUMBERNAME/./_}"
0_9.3-beta

To replace all occurrences of ., use:

$ echo "${VERSIONNUMBERNAME//./_}"
0_9_3-beta

Because this approach avoids the creation of pipelines and subshells and the use of external executables, this approach is efficient. This approach is also unicode-safe.

Documentation

From man bash:

${parameter/pattern/string}

Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If the nocasematch shell option is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list. (Emphasis added.)

Upvotes: 15

Jack
Jack

Reputation: 6178

You can combine pattern substitution with tr:

VERSION=$( echo ${VERSIONNUMBER:1} | tr '.' '_' ) 

Upvotes: 12

Related Questions