grep +与正则表达式完全匹配IP地址 [英] grep + match exactly IP address with Regular Expression
问题描述
例如I
$ more文件
192.9.200.10
192.9.200.100
192.9.200.1555
192.9.200.1
192.9.200.aaa
192.9.200。@
192.9.200 .:
192.9.200
192.9 0.200。
我需要匹配前三个八位组 - 192.9.200,而四个八位组必须有效(0- 255)
最后 - 预期结果应该是:
192.9 .200.10
192.9.200.100
192.9.200.1
基本语法应该是如下所示:
IP_ADDRESS_THREE_OCTETS = 192.9.200
cat file | grep -x $ IP_ADDRESS_THREE_OCTETS。[grep Regular Expression syntax]
请教如何编写正确的 grep正则表达式在四个八位字节中,以匹配三个八位字节,而四个八位字节必须是有效的? 解析方案
您需要使用一些高级工具将文本转换为正则表达式模式,因此您可以使用它。
perl -ne'
BEGIN {$ base = shift(@ARGV); }
如果/^\Q$base\E\.([0-9]+)$/&&& 0< = $ 1&& $ 1< = 255;
'$ IP_ADDRESS_THREE_OCTETS文件
如果硬编码基数可以接受,
perl -ne'print if /^192\.9\.200\.([0-9] +)$ /&& 0< = $ 1&& $ 1< = 255'文件
这两个片段也接受来自STDIN的输入。
完整的IP地址:
perl -ne'
BEGIN {$ ip = shift(@ARGV); }
打印如果/ ^ \ Q $ ip \ $ $;
'1.2.3.4档案
或
perl -nle'
BEGIN {$ ip = shift(@ARGV); }
打印如果$ _ eq $ ip;
'1.2.3.4档案
my target is to match exactly IP address with three octes , while the four IP octet must be valid octet - between <0 to 255>
For example I have the following IP's in file
$ more file
192.9.200.10
192.9.200.100
192.9.200.1555
192.9.200.1
192.9.200.aaa
192.9.200.@
192.9.200.:
192.9.200
192.9.200.
I need to match the first three octets - 192.9.200 while four octet must be valid ( 0-255)
so finally - expects result should be:
192.9.200.10
192.9.200.100
192.9.200.1
the basic syntax should be as the following:
IP_ADDRESS_THREE_OCTETS=192.9.200
cat file | grep -x $IP_ADDRESS_THREE_OCTETS.[ grep Regular Expression syntax ]
Please advice how to write the right "grep regular Expression" in the four octets in order to match the three octets , while the four octets must be valid?
You'd need to use some high-level tools to convert the text to a regex pattern, so you might as well use just that.
perl -ne'
BEGIN { $base = shift(@ARGV); }
print if /^\Q$base\E\.([0-9]+)$/ && 0 <= $1 && $1 <= 255;
' "$IP_ADDRESS_THREE_OCTETS" file
If hardcoding the base is acceptable, that reduces to:
perl -ne'print if /^192\.9\.200\.([0-9]+)$/ && 0 <= $1 && $1 <= 255' file
Both of these snippets also accept input from STDIN.
For a full IP address:
perl -ne'
BEGIN { $ip = shift(@ARGV); }
print if /^\Q$ip\E$/;
' 1.2.3.4 file
or
perl -nle'
BEGIN { $ip = shift(@ARGV); }
print if $_ eq $ip;
' 1.2.3.4 file
这篇关于grep +与正则表达式完全匹配IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!