Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substring of string matching regex in a bash shell [duplicate]

In a bash shell, I want to take the take a given string that matches a regex, and then take the part of the string.

For example, given https://github.com/PatrickConway/repo-name.git, I want to extract the repo-name substring.

How would I go about doing this? Should I do this all in a shell script, or is there another way to approach this?

like image 986
Patrick Conway Avatar asked Oct 26 '25 05:10

Patrick Conway


1 Answers

You can use the =~ matching operator inside a [[ ... ]] condition:

#!/bin/bash
url=https://github.com/PatrickConway/repo-name.git
if [[ $url =~ ([^/]*)\.git ]] ; then
    echo "${BASH_REMATCH[1]}"
fi

Each part enclosed in parentheses creates a capture group, the corresponding matching substring can be found in the same position in the BASH_REMATCH array.

  • [...] defines a character class
  • [/] matches a character class consisting of a single character, a slash
  • ^ negates a character class, [^/] matches anything but a slash
  • * means "zero or more times"
  • \. matches a dot, as . without a backslash matches any character

So, it reads: remember a substring of non-slashes, followed by a dot and "git".

Or maybe a simple parameter expansion:

#!/bin/bash
url=https://github.com/PatrickConway/repo-name.git
url_without_extension=${url%.git}
name=${url_without_extension##*/}
echo $name

% removes from the right, # removes from the left, doubling the symbol makes the matching greedy, i.e. wildcards try to match as much as possible.

like image 141
choroba Avatar answered Oct 28 '25 21:10

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!