如何去除尾随字符串的IP地址

how to strip IP address of trailing string

给定 IP 地址 192.168.10.21.somebody.com.br 我只需要提取 192.168.10.21 我在下面尝试了 CUT,它给出了 "cut: invalid byte or field list"。

cut -d'.' -f-4

$ echo "192.168.10.21.somebody.com.br" | cut -d'.' -f -4
192.168.10.21

适合我!

以下所有三个假设您已将域名存储在参数中

dom_name=192.168.10.21.somebody.com.br

比使用 cut 更有效,假设要删除的第一个标签不以数字开头:

echo "${dom_name%%.[[:alpha:]]*}"

如果第一个标签 可以 以数字开头,这些仍然比 cut 更有效,但更丑陋且输入时间更长:

# Match one more dot than necessary to shorten the regular expression;
# then trim that dot when echoing
[[ $dn =~ (([0-9]+\.){4}) ]]
echo "${BASH_REMATCH[1]%.}"

# Split the string into an array, then output the
# first four fields rejoined by dots.
IFS=. read -a labels <<< "$dom_name"
(IFS=.; echo "${labels[*]:0:4}")