0

I need to filter 5 IP addresses in a file. All *.tgz files.

Ip addresses are 10.85.1.1, 10.85.1.2, 10.85.1.3, 10.85.1.4, 10.85.1.5

I use this command:

zegrep -ai "10.85.1.[1-5]" *.tgz 

This returns me also for example Ip 10.85.1.45. How do I tell the command that [1-5] is the end of my string?

I thought this would do the trick:

zegrep -ai '10.85.1.[1-5]$' *.tgz

But this returns me nothing. Still, this is possible so to double check my command I tried with Ip's that are in the file (I just took tail and took one of the latest Ip's that it returned).

zegrep -ai '10.85.1.1[5-6]$' *.tgz

This also returns nothing. So my command is still not correct.

2

There are several points to make about the expressions you are trying:-

  • When you use . this will match any single character: to match . it needs to be escaped as in "10\.85\.1\.[1-5]".
  • If the decompressed file is binary (as -a implies) then you cannot assume that end-of-line will be correctly handled.
  • You could use "10\.85\.1\.[1-5][^0-9]", ie search string followed by a non-numeric character, but this will fail at end-of-line, where there is no following character.
  • The answer is to use the \< and \> word delimiters:

    zegrep -ai "\<10\.85\.1\.[1-5]\>" *.tgz

By adding the leading \< you avoid mismatches with the likes of 110.85.1.1.

Depending on your version of regular expressions, you may need to use the alternative \b word delimiter:

    zegrep -ai "\b10\.85\.1\.[1-5]\b" *.tgz
| improve this answer | |
  • Are you sure \< and \> work in POSIX regex? They seem to be vim-specific, \b is the usual format. – user1686 Sep 8 '17 at 12:05
  • @grawity - Either form works in Ubuntu. The questioner did not specify which Linux he was using, nor which grep, but he is calling zegrep, which enables extended regular expressions. Presumably he would not do this with a POSIX-compliant version, where there is no difference between basic and extended REs. – AFH Sep 8 '17 at 12:21
  • Nice! Thank you. Just one more thing. These commands give the same result: zegrep -ai "\<10\.85\.1\.[0-5]\>" *.tgz and zegrep -ai "\<10.85.1.[0-5]\>" *.tgz – maxim Sep 8 '17 at 13:14
  • 1
    That's because . matches any character including itself, but you would also get false matches for strings like 10 85 1 1 and 10,85,1,1. – AFH Sep 8 '17 at 13:22
  • @grawity - I've added the alternative \b word delimiter to my answer. Thanks for the comment. – AFH Sep 8 '17 at 13:30

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.