Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 937
tatsu Avatar asked Dec 03 '22 18:12

tatsu


2 Answers

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.)

like image 76
John1024 Avatar answered Jan 05 '23 22:01

John1024


You can combine pattern substitution with tr:

VERSION=$( echo ${VERSIONNUMBER:1} | tr '.' '_' ) 
like image 25
Jack Avatar answered Jan 05 '23 21:01

Jack