Too*_*rot 6 url string shell-script variable
在 bash 或 zsh 脚本中,如果后者在环境变量中,我如何从 url 中提取主机,例如unix.stackexchange.com
from
http://unix.stackexchange.com/questions/ask
?
您可以使用任何 POSIX 兼容 shell 中的参数扩展。
$ export FOO=http://unix.stackexchange.com/questions/ask
$ tmp="${FOO#*//}" # remove http://
$ echo "${tmp%%/*}" # remove everything after the first /
unix.stackexchange.com
Run Code Online (Sandbox Code Playgroud)
一种更可靠但更丑陋的方法是使用实际的 URL 解析器。下面是一个例子python
:
$ echo "$FOO" | python -c 'import urlparse; import sys; print urlparse.urlparse(sys.stdin.read()).netloc'
unix.stackexchange.com
Run Code Online (Sandbox Code Playgroud)
如果 URL 都遵循这种模式,我有一个简短而丑陋的 hack 给你:
echo "$FOO" | cut -d / -f 3
Run Code Online (Sandbox Code Playgroud)