Search code examples
regexbashsubstring

Bash extract project name from url github


I have the following code:

url='https://github.com/Project/name-app.git'
echo $url

I have to get this back to me, i.e. the name of the project regardless of the owner of the project.

Result:

name-app


Solution

  • You can use string manipulation in Bash:

    url='https://github.com/Project/name-app.git'
    url="${url##*/}" # Remove all up to and including last /
    url="${url%.*}"  # Remove up to the . (including) from the right
    echo "$url"
    # => name-app
    

    See the online Bash demo.

    Another approach with awk:

    url='https://github.com/Project/name-app.git'
    url=$(awk -F/ '{sub(/\..*/,"",$NF); print $NF}' <<< "$url")
    echo "$url"
    

    See this online demo. Here, the field delimiter is set to /, the last field value is taken and all after first . is removed from it (together with the .), and that result is returned.