Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SHELL :Extract a string betwen two characters in different states

Tags:

regex

bash

shell

I have a simple variable string which comes in two possibles forms :

1. First case : tag=v1.0.2-15 , or tag=v2.0.2-15 ....

2. second case : tag=v1.0.2 , or tag=v1.1.2 .....

I need to extract always the numeric part which is just after "v" and before "-" (for the first case ) and with the last numeric char (for the second case )

to obtain finally this form of output : 1.0.2 or 1.0.2 ...

I have already used this command to get it with the first case :

grep -oP "(?<=v).+(?=-)"

but i still not able to patch it for the second problem , by the way i need a command which deals with both cases in the same time any suggestions ??

like image 756
firasKoubaa Avatar asked Jan 17 '26 21:01

firasKoubaa


2 Answers

You could just use :

(?<=v)[0-9\.]+

Here's an example.

like image 199
Eric Duminil Avatar answered Jan 19 '26 18:01

Eric Duminil


grep -oP '(?<=v)[0-9]+(\.[0-9]+)*'

This looks for a v (not part of the match) followed by string consisting of one or more digits followed by one or more strings consisting of a dot followed by one or more digits.

like image 30
AlexP Avatar answered Jan 19 '26 16:01

AlexP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!