简体   繁体   English

bash脚本 - sed返回ip地址

[英]bash script - sed to return ip address

I'm developing a bash script and I'm trying to get an IPv4 address from a network interface that is ON, on this operation I'm using ip addr and sed , but something is wrong because I can't get IP from sed . 我正在开发一个bash脚本,我正试图从一个打开的网络接口获取一个IPv4地址,在这个操作上我使用的是ip addrsed ,但是出了点问题,因为我无法从sed获取IP 。

So, the script at some point have this: 所以,脚本在某些时候有这样的:

ip addr show dev eth0 | grep "inet "

This supposedly returns: 这应该归还:

inet 192.168.1.3/24 brd 192.168.1.255 scope global eth0

And with sed , I want this: 有了sed ,我想要这个:

192.168.1.3/24

I have tried some regular expressions, but it only gives error or blank lines! 我尝试了一些正则表达式,但它只给出错误或空行! How can I achieve this? 我怎样才能做到这一点?

Try this 试试这个

ip addr show dev eth0 | sed -nr 's/.*inet ([^ ]+).*/\1/p'

EDIT: Explanatory words as requested. 编辑:根据要求提供解释性词语。

-n in sed suppressed automatic printing of input line
-r turns on extended regular expressions




s/.*inet ([^ ]+).*/\1/p

Search for a anything followed by inet and a space, remember everything [that's the parentheses] that's not a space AFTER that space, followed by anything, and replace everything with the remembered thing [\\1] (the IP address), and then print that line (p). 搜索后跟inet和空格的任何内容,记住所有[这是括号],这不是该空间之后的空格,后跟任何内容,并用记住的东西[\\ 1](IP地址)替换所有内容,然后打印那条线(p)。

I know you asked for sed, so here's an answer that works using GNU sed version 4.2.1. 我知道你要求sed,所以这里有一个使用GNU sed版本4.2.1的答案。 It's really specific, and very overbaked for what you need. 它非常具体,而且非常适合您的需求。 Based on your ip addr show command, I assume this is a Linux. 基于你的ip addr show命令,我认为这是一个Linux。

ip addr show dev eth0 \
  | sed -n '/^\s\+inet\s\+/s/^\s\+inet\s\+\(.*\)\s\+brd\s.*$/\1/p'`

An easier way using awk: 使用awk更简单的方法:

ip addr show dev eth0 | awk '$1=="inet" {print $2}'

你可以使用这样的东西:

sed -e 's/^[^ ]* //' -e 's/ .*//'

使用grep直接找到你的答案。

ip addr show dev eth0 | grep -P '\d+\.\d+\.\d+.\d+\/\d+' -o

Well, both of the answers with sed and awk are quite good. 好吧,sed和awk的答案都很好。 In order to just get only the IP without the subnet mask, you could proceed further just like this: 为了只获得没有子网掩码的IP,你可以继续这样做:

ip addr show dev eth0 | sed -nr 's/.*inet ([^ ]+).*/\1/p' **| cut -f1 -d'/'**

or 要么

ip addr show dev eth0 | awk '$1=="inet" {print $2}' **| cut -f1 -d'/'**

or 要么

Even better: 更好的是:

ip route get 255.255.255.255 | grep -Po '(?<=src )(\d{1,3}.){4}'

This should output only the IP Address. 这应该只输出IP地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM