[英]Get line by index from grep output
I'm trying to get the machine's ipv4 address.我正在尝试获取机器的 ipv4 地址。 I've got this working but is there a way to specify you want index 2 from the returned data?
我已经完成了这项工作,但是有没有办法从返回的数据中指定您想要索引 2?
ip a | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"
Output Output
127.0.0.1
192.168.13.131
192.168.13.255
One option is to pipe it to sed and print the second line一种选择是 pipe 到 sed 并打印第二行
ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | sed -n 2p
Another option could be using a combination of head and tail, showing the first n items with head and then take the last item from that result.另一种选择可能是使用 head 和 tail 的组合,显示带有 head 的前 n 个项目,然后从该结果中获取最后一个项目。
ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n2 | tail -n1
If -P
is supported for pcre, you might also use a longer pattern, repeating matching the ip number n times using a quantifier, for example {2}
for repeating 2 times.如果 pcre 支持
-P
,您还可以使用更长的模式,使用量词重复匹配 ip 数 n 次,例如{2}
重复 2 次。
Then use \K
to clear the match buffer and output only the ip number of interest.然后使用
\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
With awk
, please try following, written as per your attempt.使用
awk
,请尝试按照您的尝试编写。
ip a |
awk '
match($0,/([0-9]{1,3}\.){3}[0-9]{1,3}/) && ++count==2{
print substr($0,RSTART,RLENGTH)
}'
Explanation: Adding detailed explanation for above solution.说明:为上述解决方案添加详细说明。
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.