bash 使用sed从没有前缀或后缀的主机名变量中提取域
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15213599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
extracting domain from host name variable without prefix or suffix with sed
提问by Mason Mason
I have been mucking around with this for a couple of hours and cant seem to get it working. If I have www or ftp.somedomain.net.nz or just somedomain.com and I want to extract just the somedomain from the pattern to set as a variable by echoing the hostname to sed how would I go about it?
我一直在纠结这个几个小时,但似乎无法让它工作。如果我有 www 或 ftp.somedomain.net.nz 或 somedomain.com 并且我只想从模式中提取 somedomain 以通过将主机名回显到 sed 来设置为变量,我将如何处理?
For Example:
例如:
var="echo $HOSTNAME | sed 's/someregex to fit all$//'"
采纳答案by 244an
If you know the prefixes you can try (either "ftp.", "www." or nothing):
如果您知道前缀,您可以尝试(“ftp.”、“www.”或什么都不做):
var=$(sed -E 's/^((ftp|www)\.)?([^.]*)\..*//' <<< "$HOSTNAME")
Using sed ... <<< $VARIABLEis preferred to echo $VARIABLE | sed ...
使用sed ... <<< $VARIABLE最好echo $VARIABLE | sed ...
回答by William
Do you really need to use sed?
你真的需要使用sed吗?
HOSTNAME="${HOSTNAME#*.}"
HOSTNAME="${HOSTNAME%%.*}"
Note that this, and some other solutions, won't get along with something like www.news.google.combut if you test for things like that you could do:
请注意,这个和其他一些解决方案不会与类似的东西相处,www.news.google.com但如果你测试类似的东西,你可以这样做:
HOSTNAME="${HOSTNAME#*.}"
HOSTNAME="${HOSTNAME#*.}"
HOSTNAME="${HOSTNAME%%.*}"
What works depends only how nicely formed your input is.
什么有效仅取决于您输入的格式有多好。
回答by choroba
Double quotes do not run commands. Use backquotes, or better, use $(...):
双引号不运行命令。使用反引号,或者更好地使用$(...):
var=`sed 's/[^.]*\.\([^.]*\)\..*//' <<< "$HOSTNAME"`
var=$( sed 's/[^.]*\.\([^.]*\)\..*//' <<< "$HOSTNAME" )
You probably have to tweak the regular expression to get the domain. What part of the address do you want? The examples are rather unclear. If you just want to remove www or ftp, you can use Parameter expansion:
您可能必须调整正则表达式才能获得域。你想要地址的哪一部分?这些例子相当不清楚。如果只是想去掉www或ftp,可以使用参数扩展:
var=${HOSTNAME#www.}
var=${var#ftp.}
var=${var%%.*}

