bash 脚本 - sed 返回 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15981371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash script - sed to return ip address
提问by Paulo Oliveira
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 addrand sed, but something is wrong because I can't get IP from sed.
我正在开发一个 bash 脚本,我正在尝试从打开的网络接口获取 IPv4 地址,在此操作中我使用ip addr和sed,但出现问题,因为我无法从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?
我尝试了一些正则表达式,但它只给出错误或空行!我怎样才能做到这一点?
采纳答案by tink
Try this
尝试这个
ip addr show dev eth0 | sed -nr 's/.*inet ([^ ]+).*//p'
EDIT: Explanatory words as requested.
编辑:按要求解释词。
-n in sed suppressed automatic printing of input line
-r turns on extended regular expressions
s/.*inet ([^ ]+).*//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)。
回答by ccosby
I know you asked for sed, so here's an answer that works using GNU sed version 4.2.1. It's really specific, and very overbaked for what you need. Based on your ip addr showcommand, I assume this is a Linux.
我知道您要求使用 sed,所以这里有一个适用于 GNU sed 4.2.1 版的答案。它非常具体,并且对于您的需要非常过度。根据您的ip addr show命令,我假设这是一个 Linux。
ip addr show dev eth0 \
| sed -n '/^\s\+inet\s\+/s/^\s\+inet\s\+\(.*\)\s\+brd\s.*$//p'`
An easier way using awk:
使用 awk 的更简单方法:
ip addr show dev eth0 | awk '$1=="inet" {print $2}'
ip addr show dev eth0 | awk '$1=="inet" {print $2}'
回答by kumarprd
Use grep to directly find out your answer.
使用grep直接找出你的答案。
ip addr show dev eth0 | grep -P '\d+\.\d+\.\d+.\d+\/\d+' -o
回答by Stan
Well, both of the answers with sed and awk are quite good. In order to just get only the IP without the subnet mask, you could proceed further just like this:
嗯,sed 和 awk 的两个答案都很好。为了只获取没有子网掩码的 IP,您可以像这样进一步进行:
ip addr show dev eth0 | sed -nr 's/.*inet ([^ ]+).*//p' **| cut -f1 -d'/'**
or
或者
ip addr show dev eth0 | awk '=="inet" {print }' **| 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 地址。
回答by perreal
You can use something like this:
你可以使用这样的东西:
sed -e 's/^[^ ]* //' -e 's/ .*//'

