How do you extract IP addresses from files using a regex in a linux shell?

前端 未结 19 1703
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 02:43

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 e

19条回答
  •  生来不讨喜
    2020-11-28 03:19

    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.

提交回复
热议问题