【问题标题】:Extract IP address from /etc/hosts file with SED command使用 SED 命令从 /etc/hosts 文件中提取 IP 地址
【发布时间】:2020-12-07 03:13:56
【问题描述】:

我想使用 shell sed 命令仅从我的 /etc/hosts 文件中提取 IP v4 地址。

我设法用以下命令在行尾用 localhost 隔离了这些行:

$ sed  -E '/localhost$/!d ' host_1 | sed -n 1p

这给了我以下输出:

#127.0.0.1 本地主机

如何仅从上述结果中提取 IP v4 地址?

【问题讨论】:

    标签: shell sed


    【解决方案1】:

    测试数据:

    $ cat file
    127.0.0.1 localhost
    # 127.0.0.2 localhost
    127 127.0.0.3 localhost
    

    sed:

    $ sed -n  's/\(.*[^0-9]\|\)\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+\).*/\2/p' file
    

    输出:

    127.0.0.1
    127.0.0.2
    127.0.0.3
    

    带有-E 开关的sed:

    $ sed -nE  's/(.*[^0-9]|)([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+).*/\2/p' file
    

    【讨论】:

      【解决方案2】:

      我试过这个命令,它工作正常。

      $ sed  -E '/localhost$/!d' host_1 | sed -n 1p  |grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
      

      输出:127.0.0.1

      尽管如此,我仍然对如何用 sed 命令替换 grep 感到好奇。

      【讨论】:

        【解决方案3】:
        sed  -E '/localhost$/!d '   /etc/hosts | awk '{print $1}' | grep -v :
        

        【讨论】:

        • 有没有办法使用正则表达式与 sed 命令关联来仅提取该 IPv4 地址
        • 什么意思?仅使用sed 仅此而已?当然有可能
        • 我的意思是使用 SED 和正则表达式来提取 IP 地址。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-11
        • 1970-01-01
        • 2017-10-12
        • 2014-10-06
        相关资源
        最近更新 更多