How do you extract IP addresses from files using a

2019-01-16 04:18发布

How to extract a text part by regexp in linux shell? Lets say, I have a file where in every line is an IP address, but on a different position. What is the simplest way to extract those IP addresses using common unix command-line tools?

17条回答
爷的心禁止访问
2楼-- · 2019-01-16 04:35

You can use sed. But if you know perl, that might be easier, and more useful to know in the long run:

perl -n '/(\d+\.\d+\.\d+\.\d+)/ && print "$1\n"' < file
查看更多
在下西门庆
3楼-- · 2019-01-16 04:40

Most of the examples here will match on 999.999.999.999 which is not technically a valid IP address.

The following will match on only valid IP addresses (including network and broadcast addresses).

grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file.txt

Omit the -o if you want to see the entire line that matched.

查看更多
再贱就再见
4楼-- · 2019-01-16 04:40

grep -E -o "([0-9]{1,3}[.]){3}[0-9]{1,3}"

查看更多
我命由我不由天
5楼-- · 2019-01-16 04:44

for centos6.3

ifconfig eth0 | grep 'inet addr' | awk '{print $2}' | awk 'BEGIN {FS=":"} {print $2}'

查看更多
兄弟一词,经得起流年.
6楼-- · 2019-01-16 04:46

I wrote a little script to see my log files better, it's nothing special, but might help a lot of the people who are learning perl. It does DNS lookups on the IP addresses after it extracts them.

查看更多
别忘想泡老子
7楼-- · 2019-01-16 04:46

Everyone here is using really long-handed regular expressions but actually understanding the regex of POSIX will allow you to use a small grep command like this for printing IP addresses.

grep -Eo "(([0-9]{1,3})\.){3}([0-9]{1,3})"

(Side note) This doesn't ignore invalid IPs but it is very simple.

查看更多
登录 后发表回答