Last active
April 9, 2022 04:12
-
-
Save cameronhunter/bd3d5908935dce94eeb1a2407c7a6e96 to your computer and use it in GitHub Desktop.
Parse a semver string in bash using a regular expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
## | |
# Get the major/minor/patch semver from a string. | |
# | |
# Author: Cameron Hunter <[email protected]> | |
# License: MIT 2022 | |
# | |
# Examples: | |
# semver v14.22.1 major → 14 | |
# semver v14.22.1 minor → 22 | |
# semver v14.22.1 patch → 1 | |
# semver v14.22.1 → 14 22 1 | |
## | |
function semver { | |
local string="${1}" | |
local part="${2}" | |
if [[ "${string}" =~ ^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*) ]]; then | |
case "${part}" in | |
major) echo ${BASH_REMATCH[1]} ;; | |
minor) echo ${BASH_REMATCH[2]} ;; | |
patch) echo ${BASH_REMATCH[3]} ;; | |
*) echo "${BASH_REMATCH[1]}\t${BASH_REMATCH[2]}\t${BASH_REMATCH[3]}" ;; | |
esac | |
else | |
return 1 | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment