英文:
Extracting git url's domain with POSIX
问题
我试图构建从Git仓库中提取域的最可靠方法。
对于如下的URL:
ssh://git@gitlab.com:22411/usage/project_100.git
git://example.org/path/to/repo.git
https://github.com/example/foobar.git
http://github.com/example/foobar.git
ssh://user@host.com/path/to/repo.git
git://host.com/path/to/repo.git
我可以使用:
echo $url | awk -F[/:] '{print $4}'
但对于像这样的仓库:
"git@github.com:User/UserRepo.git"
它不起作用。但以下方法可以:
echo $url | awk -v FS="(@|:)" '{print $2}'
是否有一种稳健的方法,我可以始终在POSIX中提取域?
英文:
I'm trying to build the most robust way to extract the domain from a git repo.
For urls like:
ssh://git@gitlab.com:22411/usage/project_100.git
git://example.org/path/to/repo.git
https://github.com/example/foobar.git
http://github.com/example/foobar.git
ssh://user@host.com/path/to/repo.git
git://host.com/path/to/repo.git
I can use:
echo $url | awk -F[/:] '{print $4}'
But for repos like:
"git@github.com:User/UserRepo.git"
It won't work. But the following does:
echo $url | awk -v FS="(@|:)" '{print $2}'
Is there some robust way I could always exctract the domain in POSIX?
答案1
得分: 2
如果URL包含://
,则知道要删除协议部分,然后删除从第一个/
开始的所有内容。否则,如果它包含@
,则假设它是您的第二种情况,并删除包括@
在内的所有内容,然后删除从:
开始的所有内容。其他情况可以根据需要添加。
url="..."
case $url in
*://*)
domain=${url#*://}
domain=${domain%%/*}
;;
*@*:*)
domain=${url#*@}
domain=${domain%%:*}
;;
esac
英文:
If the URL contains ://
, you know to drop the protocol, then drop everything from the first /
onwards. Otherwise, if it contains @
, assume it is your second case, and drop everything up to and including the @
, then everything from the :
onwards. Other cases can be added as necessary.
url="..."
case $url in
*://*)
domain=${url#*://}
domain=${domain#*@}
domain=${domain%%/*}
;;
*@*:*)
domain=${url#*@}
domain=${domain%%:*}
;;
esac
答案2
得分: 2
使用sed。我从s///
切换到s|||
。
sed 's|.*//||; s|.*@||; s|/.*||; s|:.*||' file
输出:
<pre>
gitlab.com
example.org
github.com
github.com
host.com
host.com
</pre>
英文:
With sed. I switched from s///
to s|||
.
sed 's|.*//||; s|.*@||; s|/.*||; s|:.*||' file
output:
<pre>
gitlab.com
example.org
github.com
github.com
host.com
host.com
</pre>
答案3
得分: 1
perl -pe 's{.*//([^/]+@)?([^:/]+).*}{$2}' input-file
英文:
Perl version :
perl -pe 's{.*//([^/]+@)?([^:/]+).*}{$2}' input-file
答案4
得分: 0
你可以很容易地使用sed
来做到这一点。
echo $url | sed -E ''s/.*\:\/\/(.*)@?.*\:.*/\1 /'' | awk -F@ ''{print $1}''
英文:
You can do that with sed
easily.
echo $url | sed -E 's/.*\:\/\/(.*)@?.*\:.*/\1 /' | awk -F@ '{print $1}'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论