-1

Given the variable

export TAG="1.3.2_release"

I want to transform the variable to the value 132.

I cant get the substring:

bash-5.0$ echo ${TAG:0:5}
> 1.3.2

And I can replace the dots with empty string:

bash-5.0$ echo ${TAG//./}
> 132_release

But I can't combine these two operations in one line:

bash-5.0$ echo ${${TAG:0:5}//./}
> bash: ${${TAG:0:5}//./}: bad substitution
vallentin
  • 23,478
  • 6
  • 59
  • 81
Henning
  • 2,202
  • 1
  • 17
  • 38
  • thank you both for the comment. I am not sure if this is the same. In your mentioned post the result of a lookup is used to adress another variable. I dont want to do that. I want to use the result of a lookup and do further operation on that. – Henning Dec 02 '19 at 16:09

3 Answers3

3

You might be able to use the following expansion :

${TAG//[^0-9]/}

It removes every non-numeric character from the variable's value.

Aaron
  • 24,009
  • 2
  • 33
  • 57
3

Why not keep it simple and create a temp variable, which holds the first substitution value in it and then create variable which has actual substituted value like:

export TAG="1.3.2_release"
var="${TAG//./}"
echo "${var/_*/}"

Since I saw your attempt of using an external command(I mean apart from bash's) then why not simple awk too

export TAG="1.3.2_release"
echo "$TAG" | awk -F'_' '{gsub(/\./,"",$1);print $1}'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • thank you, I might do that, I just wondered why it didnt work since it does in zsh. guess its not possible in bash – Henning Dec 02 '19 at 16:13
0

It possible to use cut to get just the part in front of the first _ instead of getting a substring of certain length:

bash-5.0$ echo ${TAG//./} | cut -d'_' -f 1
> 132

This is basically better than what I wanted because now the version name can be in variable length.

I still wonder though why my initial try didnt worked.

vallentin
  • 23,478
  • 6
  • 59
  • 81
Henning
  • 2,202
  • 1
  • 17
  • 38