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,000
  • 4
  • 24
  • 45

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
  • 330,190
  • 66
  • 504
  • 555
PSkocik
  • 55,062
  • 6
  • 86
  • 132
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
  • 86,341
  • 15
  • 131
  • 165
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
  • 44,338
  • 13
  • 91
  • 116
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,139
  • 5
  • 10