2

Situation

I have a file where each line has an IP address and I want to see if these Ip's are found in access.log

File name: IpAddressess

Contents example :

192.168.0.1
192.168.0.2
192.168.1.5
etc etc

Now I want to scan access.log for these IP addresses contained in the file IpAddressess

Can I use the command grep for this and what would the command structure look like?

Thank you kindly for any assistance!

1
  • 1
    Thank you, Steve! Very helpfull. Jun 26 at 15:04

2 Answers 2

2

You are looking for the -f option, described in man grep on my Arch Linux system as:

   -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.   If  this  option  is
          used  multiple  times  or  is  combined  with the -e (--regexp)
          option, search for all patterns given.  The empty file contains
          zero patterns, and therefore matches nothing.

However, since grep works with regular expressions and . in regular expressions means "any character", you will also want the -F option, so that 1.2.3 doesn't match things like 10293:

   -F, --fixed-strings
          Interpret PATTERNS as fixed strings, not regular expressions.

Putting the two together, the command you're looking for is:

grep -Ff IpAddressess access.log
2

Yes, use grep -f. Worth adding the -F to that the . character in your patterns doesn't get interpreted as 'any' character.

-f and -F is explained below

$ grep --help 2>&1|grep -i '^  \-f'
  -F, --fixed-strings       PATTERNS are strings
  -f, --file=FILE           take PATTERNS from FILE
$

Example:

$ cat patterns
192.168.0.1
192.168.0.2
192.168.1.5
$ cat myaccesslog
hello 192.168.0.1
world ! 192.168.0.2
foobar 192.168.0x1
$ grep -f patterns myaccesslog
hello 192.168.0.1
world ! 192.168.0.2
foobar 192.168.0x1
$ grep -Ff patterns myaccesslog
hello 192.168.0.1
world ! 192.168.0.2
$

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.