[英]Get line by index from grep output
我正在尝试获取机器的 ipv4 地址。 我已经完成了这项工作,但是有没有办法从返回的数据中指定您想要索引 2?
ip a | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"
Output
127.0.0.1
192.168.13.131
192.168.13.255
一种选择是 pipe 到 sed 并打印第二行
ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | sed -n 2p
另一种选择可能是使用 head 和 tail 的组合,显示带有 head 的前 n 个项目,然后从该结果中获取最后一个项目。
ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n2 | tail -n1
如果 pcre 支持-P
,您还可以使用更长的模式,使用量词重复匹配 ip 数 n 次,例如{2}
重复 2 次。
然后使用\K
清除匹配缓冲区和 output 仅 ip 感兴趣的数字。
ip a | grep -Poz "(?s)\A(?:.*?(?:[0-9]{1,3}\.){3}[0-9]{1,3}){2}.*?\K(?:[0-9]{1,3}\.){3}[0-9]{1,3}"
^^^ quantifier
使用awk
,请尝试按照您的尝试编写。
ip a |
awk '
match($0,/([0-9]{1,3}\.){3}[0-9]{1,3}/) && ++count==2{
print substr($0,RSTART,RLENGTH)
}'
说明:为上述解决方案添加详细说明。
ip a |
##Running ip a command and sending its output to awk as input
awk '
##Starting awk program from here.
match($0,/([0-9]{1,3}\.){3}[0-9]{1,3}/) && ++count==2{
##Using match function to match IP address and checking if its 2nd time coming.
print substr($0,RSTART,RLENGTH)
##Printing matching sub string here.
}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.