Bash 从 url github 中提取项目名称
Bash extract project name from url github
我有以下代码:
url='https://github.com/Project/name-app.git'
echo $url
我必须把这个还给我,即不管项目的所有者是项目的名称。
结果:
name-app
您可以使用 grep regexp:
url='https://github.com/Project/name-app.git'
echo $url | grep -oP ".*/\K[^\.]*"
你可以使用bash扩展:
url='https://github.com/Project/name-app.git'
mytemp=${url##*/}
echo ${mytemp%.*}
您可以在 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
awk
的另一种方法:
url='https://github.com/Project/name-app.git'
url=$(awk -F/ '{sub(/\..*/,"",$NF); print $NF}' <<< "$url")
echo "$url"
参见 this online demo。在这里,字段分隔符设置为 /
,最后一个字段值被取走,并且在第一个 .
之后的所有内容都从中删除(连同 .
),然后返回结果。
第一个解决方案: 使用您显示的示例,请尝试遵循 awk
代码。
echo $url | awk -F'\.|/' '{print $(NF-1)}'
OR 以确保最后一个值始终以 .git
结尾尝试在上面的代码中进行一些调整:
echo "$url" | awk -F'\.|/' '$NF=="git"{print $(NF-1)}'
第二个解决方案: 使用 sed
尝试以下操作:
echo "$url" | sed 's/.*\///;s/\..*//'
# my prefered solution
url='https://github.com/Project/name-app.git'
basename $url .git
> name-app
# others
sed 's/\(.*\/\)\([^\/]*\)\.\(\w*\)$//g' <<<$url
1.https://github.com/Project/
2.name-app
#
awk -F"[/.]" '{print $(NF-1)}' <<<$url
awk -F"[/.]" '{print }' <<<$url
tr '/.' '\n' <<<$url|tail -2|grep -v git
我有以下代码:
url='https://github.com/Project/name-app.git'
echo $url
我必须把这个还给我,即不管项目的所有者是项目的名称。
结果:
name-app
您可以使用 grep regexp:
url='https://github.com/Project/name-app.git'
echo $url | grep -oP ".*/\K[^\.]*"
你可以使用bash扩展:
url='https://github.com/Project/name-app.git'
mytemp=${url##*/}
echo ${mytemp%.*}
您可以在 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
awk
的另一种方法:
url='https://github.com/Project/name-app.git'
url=$(awk -F/ '{sub(/\..*/,"",$NF); print $NF}' <<< "$url")
echo "$url"
参见 this online demo。在这里,字段分隔符设置为 /
,最后一个字段值被取走,并且在第一个 .
之后的所有内容都从中删除(连同 .
),然后返回结果。
第一个解决方案: 使用您显示的示例,请尝试遵循 awk
代码。
echo $url | awk -F'\.|/' '{print $(NF-1)}'
OR 以确保最后一个值始终以 .git
结尾尝试在上面的代码中进行一些调整:
echo "$url" | awk -F'\.|/' '$NF=="git"{print $(NF-1)}'
第二个解决方案: 使用 sed
尝试以下操作:
echo "$url" | sed 's/.*\///;s/\..*//'
# my prefered solution
url='https://github.com/Project/name-app.git'
basename $url .git
> name-app
# others
sed 's/\(.*\/\)\([^\/]*\)\.\(\w*\)$//g' <<<$url
1.https://github.com/Project/
2.name-app
#
awk -F"[/.]" '{print $(NF-1)}' <<<$url
awk -F"[/.]" '{print }' <<<$url
tr '/.' '\n' <<<$url|tail -2|grep -v git