Skip to content

Instantly share code, notes, and snippets.

@mattmc3
Last active July 27, 2022 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmc3/f4c2e415378d980914b6c5ba19ecfcaf to your computer and use it in GitHub Desktop.
Save mattmc3/f4c2e415378d980914b6c5ba19ecfcaf to your computer and use it in GitHub Desktop.
Bash: split string on delimiter and echo substring before/after
giturls=(
mattmc3/antidote
git@github.com:mattmc3/antidote.git
https://github.com/mattmc3/antidote
)
for url in $giturls; do
url=${url%.git}
url=${url:gs/\:/\/}
user=${${url%/*}##*/}
repo=${url##*/}
echo $url $user/$repo
done
# http://tldp.org/LDP/abs/html/string-manipulation.html
function split_repo() {
local gitpath="${1:-github.com/mattmc3/myrepo}"
echo "\$gitpath = $gitpath"
echo "repo part \${gitpath##*/} = ${gitpath##*/}"
echo "user/repo \${gitpath#*/} = ${gitpath#*/}"
echo "url \${gitpath%%/*} = ${gitpath%%/*}"
echo "giturl/user \${gitpath%/*} = ${gitpath%/*}"
echo "user \${\${gitpath%/*}#*/} = ${${gitpath%/*}#*/}"
}
function split_repo2() {
local gitpath="$1"
local giturl="bbgithub.com"
local repo="${gitpath##*/}"
local usernm="${gitpath%/*}"
if [[ "$usernm" == */* ]]; then
giturl="${usernm%/*}"
usernm="${usernm#*/}"
fi
}
split_repo "bitbucket.org/joeuser/myrepo"
# split on the slash
value=start/end
echo start ${value%/*}
echo end ${value#*/}
# split on the colon
value=start:end
echo start ${value%:*}
echo end ${value#*:}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment