views:

49

answers:

3

Hello,

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.

+2  A: 

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
Tomalak
+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`
Giuseppe Cardone
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.
Tomalak
It works without escaping.
gustyaquino
@gusty: Yes, it does, but only by accident. It would match `192_168_1_102` as well, without escaping.
Tomalak
Both commands outputs the exact same result to me. Thank you.
gustyaquino
@gusty or `1925168819102`
Daniel Vandersluis
@Tomalak: very good point
gustyaquino
@Tomalak, could you edit your answer so I could accept that? since I'm new I don't know if it matter..
gustyaquino
@gusty: You're right. Done.
Tomalak
@Tomalak: i think he meant also removing useless cat, to the form Giuseppe Cardone proposed
gertas
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.
Dennis Williamson
@Dennis, OK, comment deleted. Will delete this one, too, later, so no need to confirm. ;-)
Tomalak
+2  A: 

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

sed is faster than grep on my machines

gertas
Out of interest: How much faster is it?
Tomalak
Testing with a file that has 63,000 lines, `sed` takes 1.676s and `grep` takes 4.633s
Daniel Vandersluis
just use `time` command, because it depends on platform
gertas
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`.
Dennis Williamson
A: 

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.

Bart Sas