Shell从文件中读取IP地址

时间:2015-04-22 19:00:57

标签: bash shell unix grep

我有很长的档案

Feb  2 18:43:05 os sshd[14786]: [ID 800047 auth.info] Connection closed by 2001:778:200:4280::37
Feb  2 18:46:08 os sshd[14788]: [ID 800047 auth.info] Connection closed by 158.129.0.37
Feb  2 18:48:05 os sshd[14790]: [ID 800047 auth.info] Connection closed by 2001:778:200:4280::37
Feb  2 18:48:29 os sshd[14791]: [ID 800047 auth.info] Did not receive identification string from 61.240.144.64
Feb  2 19:46:08 os sshd[14853]: [ID 800047 auth.info] Connection closed by 158.129.0.37
Feb  2 19:48:05 os sshd[14855]: [ID 800047 auth.info] Connection closed by 2001:778:200:4280::37
Feb  2 20:21:42 os sshd[14892]: [ID 800047 auth.info] Accepted keyboard-interactive for evakaz from 2001:778:200:4001:e076:812f:23e7:7e62 port 47889 ssh2
Feb  2 21:20:19 os sshd[14960]: [ID 800047 auth.info] Received disconnect from 2001:778:200:4280::38: 11: disconnected by user
Feb  2 21:21:08 os sshd[14963]: [ID 800047 auth.info] Connection closed by 158.129.0.37
Feb  2 22:31:01 os sshd[15100]: [ID 800047 auth.info] Received disconnect 
from 222.161.4.149: 11:
...
...

在每一行都有IP地址。是否可以在shell中只读取IP地址(而不是整个文件)?

2 个答案:

答案 0 :(得分:1)

对于IPv4:

$ grep -woE '([[:digit:]]+\.){3}[[:digit:]]+' file
158.129.0.37
61.240.144.64
158.129.0.37
158.129.0.37
222.161.4.149

对于IPv6:

$ grep -oE '([[:xdigit:]]+:){7}[[:xdigit:]]+' file
2001:778:200:4001:e076:812f:23e7:7e62

对于两者:

$ grep -oE '([[:xdigit:]]+:){7}[[:xdigit:]]+|([[:digit:]]+\.){3}[[:digit:]]+' file
158.129.0.37
61.240.144.64
158.129.0.37
2001:778:200:4001:e076:812f:23e7:7e62
158.129.0.37
222.161.4.149

答案 1 :(得分:1)

我建议你不要重新发明匹配IP地址的轮子:

perl -MRegexp::Common=net -nE '
    say $1 if /$RE{net}{IPv4}{-keep}/; 
    say $1 if /$RE{net}{IPv6}{-keep}/
' file

这确实需要您从CPAN安装Regexp :: Common。

从您的输入中,该命令输出

2001:778:200:4280::37
158.129.0.37
2001:778:200:4280::37
61.240.144.64
158.129.0.37
2001:778:200:4280::37
2001:778:200:4001:e076:812f:23e7:7e62
2001:778:200:4280::38
158.129.0.37
222.161.4.149