0

How to extract part of string in bash? Suppose I have a string product_name_v1.2. This name is not fixed as it can be changed. However the one thing that is certain is that there will be a version umber in the string in a format like v#.#.

What I want to do is extract the v1.2 and 1.2 from the string. Any suggestions?

Redson
  • 2,098
  • 4
  • 25
  • 50

4 Answers4

1
var=product_name_v1.2
#from the beginning strip (#) longest (##) glob ending in v (*v)
echo "${var##*v}

Bash has regexp matching too (with [[ and =~) but basic string manipulation should be enough for your use case.

(You can also check out bash(1) for more information).

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
1

In any POSIX shell, this is straightforward:

str=product_name_v1.2
version=${str##*_v}
echo $version
#=> 1.2

The construction ${name##pattern} removes the longest prefix of the contents of the parameter $name that matches the glob pattern, leaving only what comes after it.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175
1

Assuming you want to extract digits and dots from the string:

input="product_name_v1.2_more_stuff_here"
echo "${input//[^0-9.]/}"
1.2
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

There are several standard tools you may use, e.g.:

  • expr product_name_v1.2 : 'product_name_\(.*\)'
  • expr product_name_v1.2 : '.*_\(v.*\)'
  • echo product_name_v1.2 | sed -ne's/^.*_\(v[0-9.]\+\)$/\1/p'

The choice mainly depends on how complex the match needs to be. expr only supports a limited anchored regular expression match, which suffices in the examples above.

Thomas B Preusser
  • 1,159
  • 5
  • 10