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

前端 未结 19 1665
被撕碎了的回忆
被撕碎了的回忆 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:31

    For those who want a ready solution for getting IP addresses from apache log and listing occurences of how many times IP address has visited website, use this line:

    grep -Eo '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' error.log | sort | uniq -c | sort -nr > occurences.txt
    

    Nice method to ban hackers. Next you can:

    1. Delete lines with less than 20 visits
    2. Using regexp cut till single space so you will have only IP addresses
    3. Using regexp cut 1-3 last numbers of IP addresses so you will have only network addresses
    4. Add deny from and a space at the beginning of each line
    5. Put the result file as .htaccess

提交回复
热议问题