0

I have a big apache log file and I need to filter that and leave only (in a new file) the log from a certain IP: 192.168.1.102

I try using this command:

sed -e "/^192.168.1.102/d" < input.txt > output.txt

But "/d" removes those entries, and I needt to leave them.

Thanks.

1
  • 1
    Don't forget that the dot (.) has meaning in a regular expression so you need to escape it if you want a literal dot. Commented Sep 20, 2010 at 14:44

3 Answers 3

2

What about using grep?

cat input.txt | grep -e "^192.168.1.102" > output.txt

EDIT: As noted in the comments below, escaping the dots in the regex is necessary to make it correct. Escaping in the regex is done with backslashes:

cat input.txt | grep -e "^192\.168\.1\.102" > output.txt
Sign up to request clarification or add additional context in comments.

8 Comments

+1, grep is the right tool. There's no need to use cat, it just slows things down, and "." should be escaped: grep -e "^192\.168\.1\.102" input.txt > output.txt
PS: As @Daniel Vandersluis correctly noted, you need to escape the dots in the regex. Escaping rules may depend on the command interpreter you are using, usually escaping is done by a backslash.
@gusty: Yes, it does, but only by accident. It would match 192_168_1_102 as well, without escaping.
@Tomalak, could you edit your answer so I could accept that? since I'm new I don't know if it matter..
You can do it without escaping the dots like this: grep -F '192.168.1.102' which sees the dots as literal, but you can't anchor it to the beginning of the line this way.
|
2

sed -n 's/^192\.168\.1\.102/&/p'

sed is faster than grep on my machines

3 Comments

Out of interest: How much faster is it?
Testing with a file that has 63,000 lines, sed takes 1.676s and grep takes 4.633s
It's not necessary to do a substitution: sed -n /^192\.168\.1\.102/p' input.txt. The speed depends on the pattern. By varying the pattern, I got some results that were faster for sed and some for grep.
0

I think using grep is the best solution but if you want to use sed you can do it like this:

sed -e '/^192\.168\.1\.102/b' -e 'd'

The b command will skip all following commands if the regex matches and the d command will thus delete the lines for which the regex did not match.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.