I am trying to get the branch name using regex and then use it in a case.
Does anyone know how it could work?
Possible names are:
- release/v1.1 -> release
- master -> master
- develop -> develop
BRANCH="release/v1.1";
#BRANCH="master";
#BRANCH="develop";
#branch_name=`expr "${BRANCH}" : '^\(release\)\/v[0-9]\.[0-9]$'`
branch_name=`expr "${BRANCH}" : '^\(master)|(release\)\/v[0-9]\.[0-9]$'`
echo $branch_name
CodePudding user response:
What about cut
?
| cut -f1 -d"/"
This uses a slash as a separator and only shows the first entry:
Prompt> echo "master" | cut -f1 -d"/"
master
Prompt> echo "develop" | cut -f1 -d"/"
develop
Prompt> echo "release/v1.1 you can put whatever here :-)" | cut -f1 -d"/"
release
Edit: In order to use this to assign to variable branch_name
, this is what you need to do:
branch_name=$(echo $BRANCH | cut -f1 -d"/")
CodePudding user response:
You can also use sed and put every alternative in it's own group
The part ((release)/v[0-9] (\.[0-9] )?
matches release followed by /
and 1 digits, optionally followed by .
and 1 digits.
In the replacement use group 2 and group 4.
for BRANCH in release/v1.1 master develop; do
sed -E 's~^((release)/v[0-9] (\.[0-9] )?|(develop|master))$~\2\4~' <<< "$BRANCH"
done
Output
release
master
develop
See the regex groups.
You could also use a bit shorter version of the pattern with awk, setting the field separator to /
and when there is a match print field 1.
awk -F'/' '/^(release\/v[0-9] (\.[0-9] )?|develop|master)$/ {print $1}' <<< "$BRANCH"