【问题标题】:Linux print multiple IP Address (ifconfig) in 1 line outputLinux 在 1 行输出中打印多个 IP 地址(ifconfig)
【发布时间】:2017-11-16 17:07:38
【问题描述】:

这是标准的 Linux ifconfig 命令

user@linux:~$ ifconfig 
eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:10  
          inet addr:192.168.1.1  Bcast:192.168.56.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:112 errors:0 dropped:0 overruns:0 frame:0
          TX packets:93 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:14616 (14.2 KiB)  TX bytes:17776 (17.3 KiB)

eth1      Link encap:Ethernet  HWaddr 00:00:00:00:00:11
          inet addr:10.0.1.1  Bcast:10.0.1.255  Mask:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

user@linux:~$

这是从 ifconfig 中仅打印 IP 地址

user@linux:~$ cat script.sh
ifconfig | grep ad.*Bc | cut -d: -f2 | awk '{ print $1}'
user@linux:~$ 

输出如下所示

user@linux:~$ ./script.sh
192.168.1.1
10.0.1.1
user@linux:~$

我想要完成的是在 1 行中打印 IP 地址的输出......类似这样。

user@linux:~$ ./script2.sh
192.168.1.1 10.0.1.1
user@linux:~$

ifconfig 可以吗?如果是的话,如果你能分享这个技巧,我将不胜感激。谢谢

【问题讨论】:

  • @manishr,那是不同的。那是只打印 IP 地址的输出(默认是在新行中打印每个 IP 地址,而不是在 1 行中)。顺便说一句,我也已经在该链接上提供了答案。您可能想再次检查该链接。谢谢 我在这里要完成的是在 1 行中打印 IP 地址的输出,而 zhenguoli 已经提供了准确的答案

标签: linux awk ifconfig


【解决方案1】:
ifconfig | awk '{match($0,/inet addr:([^ ]+)/,a);x=x FS a[1]}END {print x} '
  142.133.152.191         127.0.0.1

或者使用grep

ifconfig | grep -oP 'inet addr:\K[^ ]+' | xargs
142.133.152.191 127.0.0.1

【讨论】:

    【解决方案2】:
    ifconfig | grep ad.*Bc | cut -d: -f2 | awk '{ print $1}' | { tr '\n' ' '; echo; }
    

    您的代码几乎可以正常工作。只需将换行符转换为空格并添加更多换行符即可。

    【讨论】:

    • 打败我,+1
    【解决方案3】:

    如果你有hostname

    hostname -I
    

    测试:

    $ hostname -I
    192.168.2.253 192.168.0.179
    

    【讨论】:

    • -I(大写)在此框中不支持 user@BusyBox:~$ 主机名 -I 主机名:无效选项 -- 'I' BusyBox v1.24.2 (2016-05-16 13:46 :43 UTC) 多呼叫二进制。用法:主机名 [选项] [主机名 | -F FILE] 获取或设置主机名或 DNS 域名 -s Short -i 主机名地址 -d DNS 域名 -f 完全限定域名 -F FILE 使用 FILE 的内容作为主机名 user@BusyBox:~$
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2010-12-21
    • 2018-07-04
    • 2014-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多