Only get the first part of grep: get ip of ifconfig

时间:2019-04-16 23:16:05

标签: linux bash shell grep ifconfig

ifconfig | grep -m1 "inet addr" 

Gives me

inet addr:172.30.1.6  Bcast:172.30.140.255  Mask:255.255.252.0

However, I only want the ip, which is 172.30.1.6. How can I do this? Note that I have to be using ifconfig, as this is an embedded system with limited functionalities.

8 个答案:

答案 0 :(得分:5)

Get out your scissors, it's cuttin' time.

echo inet addr:172.30.1.6  Bcast:172.30.140.255  Mask:255.255.252.0 | cut -d : -f 2 | cut -d " " -f 1

答案 1 :(得分:4)

One way to do it ..

ifconfig | grep -m1 "inet addr" | awk '{print $2}' | awk -F: '{print $2}'

答案 2 :(得分:4)

If all you want to do is obtain the ip address, there might be easier ways of achieving that using say hostname -i ( reference Which terminal command to get just IP address and nothing else? )

Since others have mentioned cut and awk, I will provide a solution using sed :

echo "inet addr:172.30.1.6  Bcast:172.30.140.255  Mask:255.255.252.0" | sed -e "s/.*\(addr:[^ ]*\) .*/\1/"

addr:172.30.1.6

echo "inet addr:172.30.1.6  Bcast:172.30.140.255  Mask:255.255.252.0" | sed -e "s/.*addr:\([^ ]*\) .*/\1/" 

172.30.1.6

答案 3 :(得分:2)

Use cut with a delimiter

| cut -d':' -f 2 | cut -d' ' -f 1

答案 4 :(得分:2)

这就是您要尝试的全部吗?

awk -F'[: ]' '/inet addr/{print $3; exit}'

例如使用cat file代替ifconfig

$ cat file
inet addr:172.30.1.6  Bcast:172.30.140.255  Mask:255.255.252.0

$ cat file | awk -F'[: ]' '/inet addr/{print $3; exit}'
172.30.1.6

答案 5 :(得分:1)

Just use the command cut.

ip a | grep -m1 "inet addr" | cut -d':' -f 2 | cut -d' ' -f 1 

I also advise you to learn the use of other commands such as : wc,sed,tr,sort,uniq. They will help manipulate the output as you please. Here is a small lesson where we present you all these command : https://www.javatpoint.com/linux-filters

I hope to help you.

答案 6 :(得分:1)

使用Bash的正则表达式运算符=~

$ [[ $(ifconfig | grep -m1 "inet addr") =~ [0-9]+\.[0-9]+\.[0-9]+\.[0-9]+ ]] && echo ${BASH_REMATCH[0]}
172.30.1.6

更新:评论中甚至更好。

答案 7 :(得分:1)

这是一种通过单个sed命令执行此操作的方法,从而消除了对grep的调用:

ifconfig | sed -n '/inet addr/{s/^.*inet addr:\([^ ]*\).*$/\1/p;q}'

这里发生了一些事情:

  • sed -n告诉sed不要像往常一样打印每一行
  • /inet addr/是一个sed地址-它告诉sed仅对包含"inet addr"的行进行操作
  • {}括号定义了要运行的命令块,命令之间用;隔开
  • s命令非常简单-它仅捕获IP并将整个行替换为IP
  • p命令末尾的s 标志告诉sed打印替换结果。这是必要的,因为我们使用sed选项调用了-n
  • q命令告诉sed退出,因此它仅处理包含"inet addr" first 行。

使用-n选项,/inet addr/地址,p命令上的s标志和q命令,实际上具有相同的效果为grep -m1 "inet addr",这样就不需要调用grep。实际上,值得注意的是以下命令会产生相同的输出:

> ifconfig | grep -m1 "inet addr"
         inet addr:192.168.1.1  Bcast:192.168.2.255  Mask:255.255.255.0

> ifconfig | sed -n '/inet addr/{p;q}'
         inet addr:192.168.1.1  Bcast:192.168.2.255  Mask:255.255.255.0

在这里,我省略了s/pattern/replacement/p命令的sed部分,而将其替换为p命令(仅打印整行),只是为了显示效果隔离的其他部分。