1

I would like to know if there is any command line tool to search text files preloaded with some well-known regexes (IP, email, date, path, url, xml tags, etc) so you could do something like:

grep -A 5 '443: open' somefile.log | getregexmatch --ip

To extract all the IP addresses from the output of grep.

  • What is the well-known regex for email? – MatthewRock Mar 7 '16 at 12:59
  • @StéphaneChazelas I want to extract the IP without cut, AWK and other similar tools im using right now – Hidden Mar 7 '16 at 13:03
  • @StéphaneChazelas You are right, thank you. – Hidden Mar 7 '16 at 13:10
  • Note that IP may not be a very good choice of an example here as there are so many ways to represent IP (IPv4 and IPv6) addresses. For instance, here, would that mean IPv4 addresses in quad-decimal (accepting leading 0s) notation or any standard representation of IPv4 or IPv6 IP addresses? Would it find a 0.0.0.0 IP address in foo0.0.0.0bar or 0.0.0.0.0 or (0.0.0.0), or only as whole blank-separated words... – Stéphane Chazelas Mar 7 '16 at 13:56
  • @StéphaneChazelas I think IP is a perfect example. I know there are a thousand ways to represent IP, as there are a thousand ways to represent an email (using IP instead of a domain for example), a date (hypens or slashes) or path (back slash, fordward slash, escaped slashes, ...) but I'm not looking for a comprehensive list of regexes to cover every corner case (I know how to write my own regex for that scenarios), just a simple tool to save myself some typing on regular cases. – Hidden Mar 7 '16 at 14:15
3

Yes, perl is your friend. In this case perl's Regexp::Common in particular. It provides predefined regex definitions (see the documentation for more details : http://search.cpan.org/~abigail/Regexp-Common-2016020301/lib/Regexp/Common.pm).

An IPv4 example would be :

$ perl -MRegexp::Common -lne 'print $1 if /($RE{net}{IPv4})/g' file
172.18.0.1
172.17.0.1
127.0.0.1
  • Probably better with perl -MRegexp::Common -lne 'print for /$RE{net}{IPv4}/g' to return all the matches. – Stéphane Chazelas Mar 7 '16 at 16:57
  • @StéphaneChazelas good point. Will correct the answer. – KWubbufetowicz Mar 7 '16 at 17:28
  • Not exactly what I was looking for but probably the closest solution. Thank you both. – Hidden Mar 7 '16 at 21:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.