Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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'?

share|improve this question

3 Answers 3

up vote 3 down vote accepted
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.

share|improve this answer
    
Note that grep -E '(a|b)' is standard and portable but grep '\(a\|b\)' is not. –  Stéphane Chazelas Feb 25 at 20:19
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
share|improve this answer

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.

share|improve this answer
1  
cat, really...? –  Hauke Laging Feb 25 at 18:47
    
@HaukeLaging : Tch, point taken :) –  goldilocks Feb 25 at 18:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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