IPアドレス表示でのIP GreppingとSedding

IPアドレス表示でのIP GreppingとSedding

Arch仮想マシンのローカルIPを取得しようとしています。私はgrepを使って欲しいものを含む行を得ましたが、sedを使って行をトリミングしたいと思います。

inet <<192.168.0.16>>/24 brd 192.1680.255 scope global enp0s3 $ I want the IP in <<>>
ip addr show | grep 'inet\ ' | sed -n -e 's/^.*inet\ (.*)\/.*$/\1/p'
-n     # print nothing by default
s      # replacement command
^      # begin line
.*     # anything
inet\  # inet and then a space
(.*)   # capture anything
\/     # end capture at the / that comes before 24
.*     # anything
$      # end
\1     # replace all that with the first capture group which should be the IP
p      # print the output

しかし、一度sedを追加すると、何も提供されません。正規表現に問題があるようです。

ベストアンサー1

awkこれはgrepandを使用するよりも簡単ですsed

ip addr show eth0 | awk '/inet / {print $2}'

IPからCIDRネットマスクを削除する場合:

ip addr show eth0 | awk '/inet / {gsub(/\/.*/,"",$2); print $2}'

インターフェイスには複数のIPアドレスがあります。たとえば、ip addr show br0 | awk '/inet / {print $2}'私のシステムには11のIPv4アドレスがあり、その一部はパブリックIPアドレス、一部はRFC1918プライベートアドレスです。

おすすめ記事