Reputation: 220
I have the following IP addresses in a file
3.3.3.1
3.3.3.11
3.3.3.111
I am using this file as input file to another program. In that program it will grep
each IP address. But when I grep
the contents I am getting some wrong outputs.
like
cat testfile | grep -o 3.3.3.1
but I am getting output like
3.3.3.1
3.3.3.1
3.3.3.1
I just want to get the exact output. How can I do that with grep
?
Upvotes: 2
Views: 787
Reputation: 174874
You may use anhcors.
grep '^3\.3\.3\.1$' file
Since by default grep uses regex, you need to escape the dots in-order to make grep to match literal dot character.
Upvotes: 0
Reputation: 158280
Use the following command:
grep -owF "3.3.3.1" tesfile
-o
returns the match only and not the whole line.-w
greps for whole words, meaning the match must be enclosed in non word chars like <space>
, <tab>
, ,
, ;
the start or the end of the line etc. It prevents grep from matching 3.3.3.1
out of 3.3.3.111
.
-F
greps for fixed strings instead of patterns. This prevents the .
in the IP address to be interpreted as any char, meaning grep
will not match 3a3b3c1
(or something like this).
Upvotes: 4
Reputation: 5315
To match whole words only, use grep -ow 3.3.3.1 testfile
UPDATE: Use the solution provided by hek2mgl as it is more robust.
Upvotes: 1