【问题标题】:Get line by index from grep output从 grep 输出中按索引获取行
【发布时间】:2021-07-23 20:14:10
【问题描述】:

我正在尝试获取机器的 ipv4 地址。 我已经完成了这项工作,但有没有办法从返回的数据中指定您想要索引 2?

ip a | grep -E -o "([0-9]{1,3}[\.]){3}[0-9]{1,3}"

输出

127.0.0.1
192.168.13.131
192.168.13.255

【问题讨论】:

  • 可能使用 head 从顶部获取 2 行,然后使用 tail -n1 从 ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n2 | tail -n1 获取最后一行,或者将其通过管道传输到 sed 并打印第 2 行 ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | sed -n 2p

标签: regex linux grep ip


【解决方案1】:

使用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.
}'

【讨论】:

    【解决方案2】:

    一种选择是将其通过管道传输到 sed 并打印第二行

    ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | sed -n 2p
    

    另一个选项可能是使用 head 和 tail 的组合,显示前 n 个带有 head 的项目,然后从该结果中取出最后一个项目。

    ip a | grep -Eo "([0-9]{1,3}\.){3}[0-9]{1,3}" | head -n2 | tail -n1
    

    如果 pcre 支持 -P,您还可以使用更长的模式,使用量词重复匹配 ip 号 n 次,例如 {2} 重复 2 次。

    然后使用\K清空匹配缓冲区,只输出感兴趣的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2020-01-21
      • 1970-01-01
      • 2014-02-20
      • 2017-03-26
      • 2016-05-16
      相关资源
      最近更新 更多