Omar Abid
Omar Abid

Reputation: 15976

How to extract a substring from a URL in bash

I have the following string

[email protected]:user/my-repo-name.git

I want to extract this part

my-repo-name

Upvotes: 1

Views: 1149

Answers (2)

Cyrus
Cyrus

Reputation: 88591

With bash:

s='[email protected]:user/my-repo-name.git'
[[ $s =~ ^.*/(.*)\.git$ ]]
echo ${BASH_REMATCH[1]}

Output:

my-repo-name

Upvotes: 5

Jeff Ames
Jeff Ames

Reputation: 1446

Another method, using bash's variable substitution:

s='[email protected]:user/my-repo-name.git'
s1=${s#*/}
echo ${s1%.git} 

Output:

my-repo-name

I'm not sure if there's a way to combine the # and % operators into a single substitution.

Upvotes: 3

Related Questions