簡體   English   中英

從 grep output 按索引獲取行

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM