简体   繁体   English

获取最后一个网段的IP地址

[英]Get last segment IP address

In Bash can I get the last segment of an IP address by 在Bash中,我可以通过以下方式获取IP地址的最后一段:

$ A="10.10.10.46"
$ echo ${A##*.}
46

Can something similar easy be done in Perl? 在Perl中可以轻松完成类似的事情吗?

You can get last octet by matching numbers to the end of the string, 您可以通过将数字匹配到字符串的末尾来获取最后一个八位位组,

my $A = "10.10.10.46";
print $1 if $A =~ /([0-9]+)$/;

or by splitting on dot char and selecting last list element, 或通过分割点字符并选择最后一个列表元素,

my $num = ( split /[.]/, $A )[-1];

In Perl: 在Perl中:

my $a = "10.10.10.46";
print $1 if $a =~ /\.(\d{1,3})$/;

This regex will match the last 1 to 3 digits, and will make sure there's a dot in front of them. 此正则表达式将匹配最后1到3位数字,并确保它们前面有一个点。

In perl use substr 在perl中使用substr

my $str1 = "10.10.10.46";
$out1 = substr($str1, -2);

Now suppose you have more than 2 digits; 现在假设您有两位以上的数字;

To get everything after the last dot 在最后一个点之后获取所有内容

(?<=\.)\d+$

You can for example use this in perl : 例如,您可以在perl使用它:

my $A="10.10.10.46";
my @d = split(/\./, $A);
print $d[-1];

This will always print the last element based on . 这将始终基于打印最后一个元素. as separator. 作为分隔符。 It does slice the string in pieces based on . 它确实基于分割字符串. and then prints the last element of the subsequent array. 然后打印后续数组的最后一个元素。

您想将所有数字都放在字符串的末尾,因此要求。

($n) = $ip =~ /(\d+)$/;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM