mac 指定したファイルからIPアドレスのみを抽出する

  • 作成日 2023.12.16
  • mac
mac 指定したファイルからIPアドレスのみを抽出する

macのターミナル上で、指定したファイルからIPアドレスのみを抽出する手順を記述してます。「grep」コマンドのオプション「Eo」を使用して正規表現で抽出します。

環境

  • OS macOS Monterey
  • SHELL /bin/zsh

手順

ファイルからIPアドレスだけを抜き出すには、「grep」で正規表現を使用します。
実際に、ipアドレスが記述されている以下の「/etc/hosts」ファイルからIPアドレスだけを抽出してみます。

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost
# Added by Docker Desktop
# To allow the same kube context to work on the host and the container:
127.0.0.1 kubernetes.docker.internal
# End of section
111.111.111.111 hoge.com

抽出してみます。

grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' /etc/hosts

<出力結果>
127.0.0.1
255.255.255.255
127.0.0.1
111.111.111.111

IPアドレスだけが抽出されていることが確認できます。