This is for an assignment so I have no choice but to use sed.
Given a file messages, how can I extract all the IP addresses and print them?
I first
Use sed -r
(extended regex) or escape the capture groups with \
You can do that too:
Windows:
ipconfig | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1' | sed '2 d' | head -n1;
OSX:
ifconfig | perl -nle'/(\d+\.\d+\.\d+\.\d+)/ && print $1' | sed '1 d' | head -n1;
If you have GNU sed
, you could simply add the -r
flag to use EREs:
sed -rn '/((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])/p' file
Otherwise, you will need to escape certain characters:
sed -n '/\(\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)\.\)\{3\}\(1\?[0-9][0-9]\?\|2[0-4][0-9]\|25[0-5]\)/p' file
These characters include:
(
, )
{
, }
|
?
Generally (although not for your case) I use the following to match IP address:
sed -rn '/([0-9]{1,3}\.){3}[0-9]{1,3}/p' file
Or in compatibility mode:
sed -n '/\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}/p' file
grep will be more suitable there (if you have sed
, you should have grep
too):
grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' messages
This is your own regex
with no modification (tested OK)
If you use git-bash
on Windows
. It is quite handy.
export LC_ALL=C; ipconfig | sed -n 's/IPv4//gp;' | sed -En 's/.*(10.*)/\1/gp'
以太网适配器 VMware Network Adapter VMnet1:
连接特定的 DNS 后缀 . . . . . . . :
本地链接 IPv6 地址. . . . . . . . : fe80::3177:bf7b:590:c787%6
IPv4 地址 . . . . . . . . . . . . : 192.168.31.1
子网掩码 . . . . . . . . . . . . : 255.255.255.0
默认网关. . . . . . . . . . . . . :
以太网适配器 VMware Network Adapter VMnet8:
连接特定的 DNS 后缀 . . . . . . . :
本地链接 IPv6 地址. . . . . . . . : fe80::c8de:747e:34fe:58cd%12
IPv4 地址 . . . . . . . . . . . . : 192.168.239.1
子网掩码 . . . . . . . . . . . . : 255.255.255.0
默认网关. . . . . . . . . . . . . :
以太网适配器 以太网:
连接特定的 DNS 后缀 . . . . . . . : some.com
本地链接 IPv6 地址. . . . . . . . : fe80::9d9:bb4d:e77a:3a98%15
IPv4 地址 . . . . . . . . . . . . : 10.11.68.42
子网掩码 . . . . . . . . . . . . : 255.255.254.0
默认网关. . . . . . . . . . . . . : 10.11.168.1
The script will only give you the 10
prefixed ip
address 10.11.68.42
.
The script can be explained to be
match lines contain
IPv4
and substituteIPv4
with blank and print, then capture something prefixed with10
and print it