Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieve version number from file follow string

I want to be able to retrieve a version number (n.n.n) from a file (yaml) that follows a string.

sdk: ">=0.2.4 <3.1.1"
version: ^2.3.1
sdk: flutter
version: 1.0.0+1

sed -n '/version:/p sample.yaml

which returns the line for the string provided "version:", I then piped this into another command grep to pattern match the line for the version number:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

sed -n '/version:/p sample.yaml | grep -oP '(\[0-9\]+).(\[0-9\]+).(\[0-9\]+)'

I would like to see if there is a more efficient way to do this, and if string = ‘sdk’ from the example the returned value returns both when I would like to return a single value.

>Solution :

You can use

sed -nE 's/.*version:[^0-9]*([0-9][0-9.]*).*/\1/p' file
grep -oP 'version:\D*\K\d[\d.]*' file

See an online demo:

#!/bin/bash
s='sdk: ">=0.2.4 <3.1.1"
version: ^2.3.1
sdk: flutter
version 1.0.0+1'
sed -nE 's/.*version:[^0-9]*([0-9][0-9.]*).*/\1/p' <<< "$s"
# => 2.3.1
grep -oP 'version:\D*\K\d[\d.]*' <<< "$s"
# => 2.3.1

The version:\D*\K\d[\d.]* grep regex matches version: substring, then any zero or more non-digits (with \D*), then omits the matched text (with \K) and then matches and returns a digit and then any zero or more digits or dots (with \d[\d.]*).

The sed POSIX ERE (see -E option enabling this regex flavor) pattern matches

  • .* – any text
  • version: – a fixed substring
  • [^0-9]* – zero or more non-digits
  • ([0-9][0-9.]*) – Group 1 (\1): a digit and then zero or more digits or dots
  • .* – any text.

The whole match is replaced with Group 1 value, the p flag prints the result of the successful substitution (-n suppresses default line output).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading