0

What I'm trying to do is use grep to search my Apache logs. What I want is to find is every entry from a certain IP address that also has .html or .php in the line. In other words, I want to see what pages they've accessed without all of the Javascript, CSS, and images included.

I know I can search for the lines with the IP address with grep '123.123.123.123' logfile but how I can add to the pattern so that it will only match lines that include the IP address, and '.php' or '.html'?

3
grep '123\.123\.123\.123.*\(\.php\|\.html\)' logfile

Unless of course the .php or .html precedes the IP address:

grep '\(\.php\|\.html\).*123\.123\.123\.123' logfile

You can always craft a regex that does both, but a simple option is just to use two greps:

grep '123\.123\.123\.123' logfile | grep '\.php\|\.html'

Note the \. which I originally forgot matches an actual dot, while a dot on its own matches any character. It may be easier to omit the \ since it is easier to type and unlikely to cause problems. Also grep -F, as with Hauke's answer will match fixed strings, no need for \ there. grep -E can also be used to enable extended expressions, meaning the \ before each parenthesis or the | should be omitted.

  • Note that grep -E '(a|b)' is standard and portable but grep '\(a\|b\)' is not. – Stéphane Chazelas Feb 25 '14 at 20:19
2
echo 123.123.123.123 foo.html | grep -E '123\.123\.123\.123.*\.(php|html)'

or, maybe faster

echo 123.123.123.123 foo.html | grep -F 123.123.123.123 | \
  grep -F -e .php -e .html
1

Pipe the two searches together:

grep '123\.123\.123\.123' whatever.log | grep -P "php|html"

The first grep picks lines with the ip, then the second one filters those for lines that contain "php" or "html".

Note that for this to work you need a PCRE capable grep (hence -P switch in the 2nd grep). Graeme's answer contains a variant that doesn't rely on this.

  • 1
    cat, really...? – Hauke Laging Feb 25 '14 at 18:47
  • @HaukeLaging : Tch, point taken :) – goldilocks Feb 25 '14 at 18:49

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.