Home > Mobile >  Check for version number after string and error if no version number found
Check for version number after string and error if no version number found

Time:05-16

Currently looking for a better way of doing this...

Say for example I had a file that contains a string with either a branch name or version number. I would like to catch if the file does not use a version number after the ref pattern.

example file:

source = "git::https://URL?ref=main"
source = "git::https://URL?ref=0.1.0"

Currently I am doing it like so:

# Search for string after pattern and turn it into an array.
version=($(grep -oP '(?<=ref=).*' file.txt | tr -d '".'))

# If array does not contain number pattern, catch it.
if [[ $version =~ ^[0-9] (\.[0-9] ){2,3}$ ]]
then
  echo "All module sources contain versions, will continue"
else
  echo "Some module sources DO NOT contain versions, you must use a version number in your module source"
fi

How can I do this with grep alone, or even with having to export the string to an array?

CodePudding user response:

if grep -E 'ref=[0-9].[0-9]{2,3}$'; then
   echo has version
else
   echo has no version

CodePudding user response:

I ended up with

if [[ $(grep -oPr '(?<=ref=).*' | tr -d '"') =~ ^[0-9] (\.[0-9] ){2,3}$ ]]
then
  echo "All module sources contain versions, will continue"
else
  echo "Some module sources DO NOT contain versions, you must use a version number in your module source"
fi
  • Related