![](/img/trans.png)
[英]How can I select the IP address from the output of the `ip route` command using 'src'
[英]How can I select the IP address from the output of the `ip route` command?
$ ip route得到255.255.255.255
廣播255.255.255.255 dev eth0 src 192.168.223.129
我想獲取的IP地址為192.168.223.129
我所知道的是我必須使用sed
命令。 另外,能否請您描述所使用的命令?
如果我要提取文本,那么第一件事就是grep / ack。
嘗試這個:
ip route get 255.255.255.255|grep -oP '(?<=src ).*'
這個模式匹配問題是grep
最簡單,最適合的工具。
您要匹配的是單詞src
的IP地址。 您可以使用此正則表達式來匹配IP地址: (\\d{1,3}.){4}
並在后面使用正向后確保IP地址遵循單詞src
例如(?<=src )
:
$ ip route get 255.255.255.255 | grep -Po '(?<=src )(\d{1,3}.){4}'
192.168.223.129
要在grep
使用正向查找,您需要對perl正則表達式使用-P
標志,並且-o
標志告訴grep
僅顯示行的匹配部分,因為grep
的默認行為是顯示包含匹配項的整行。
此解決方案與ip route get 255.255.255.255
的輸出無關,因為您正在搜索,並且IP地址緊隨單詞src
,而不依賴於輸出格式(例如恰好是第一行的最后一個單詞)。
使用AWK更容易解決此問題。 假設這不是一項家庭作業,請使用正確的工具完成工作! 例如,要將IP地址存儲在變量中以備后用,可以執行以下操作:
ip_address=$(
ip route get 255.255.255.255 |
awk '{print $NF; exit}'
)
然后,您可以通過新變量訪問值。 例如:
$ echo "$ip_address"
192.168.1.1
如果可以使用out sed
,則可以使用以下方法: ip route
輸出
[aman@aman ~]$ ip route get 255.255.255.255
broadcast 255.255.255.255 dev wlan0 src 192.168.1.4
cache <local,brd>
獲取ip
地址
[aman@aman ~]$ ip route get 255.255.255.255|head -1|cut -f7 -d' '
192.168.1.4
使用sed,您可以這樣做:
ip route get 255.255.255.255 | sed -n '/src/ s/.*src //p'
-n
禁止輸出。 /src/
位選擇執行替換s///
並在其上打印p
命令的行。 替換命令s/.*src //
除去一切至多且包括src
(注意結尾間隔)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.