Search code examples
bashshell

Extract a string betwen two characters of bigger string with "cut" or "sed"


I have a simple variable string which comes in this form: tag=v1.0.2-15 , or tag=v2.0.2-15 ....

I want to extract from it the part just after "v" and before "-" to obtain always the number part (= between "v" and "_")

this: 1.0.2

I used:

$ echo (tag=v1.0.2-15 | sed -n '/tag=v/,/-/p')

and

$ echo (tag=v1.0.2-15 | cut -d'v' -f 2)

but that didn't work for the moment.

Any other simple solutions?


Solution

  • One option would be to remove the parts before the v and after the -, using sed:

    $ sed 's/.*v\|-.*//g' <<<'tag=v1.0.2-15'
    1.0.2
    

    This matches anything followed by a v, or anything after a - and replaces with nothing, leaving you with the part you're interested in.