Skip to content
Advertisement

Grep regexp for matching ip addresses in a file

I’m trying to search a file “Sessions” that contains IP addresses (among other useless junk). My Grep is failing to match, even though REGEXR is matching perfectly all the IPs perfectly … so I know the REGEX is correct … but when I GREP for this same pattern, not is returned.

for i in $(grep --regexp=[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3} sessions); do echo $i; done

I’ve tried a variation of ways on that GREP (without the long options)

for i in $(grep '^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}$' sessions); do echo $i; done

for i in $(grep "[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}" sessions); do echo $i; done

I don’t understand. I’ve read the man page and also tried egrep as well. Here is a sample of what I’m searching …

SEGMENT=#109#0%111.111.111.111%22%USER%%-1%-1% %%22%%0%-1%Interactive shell%
SEGMENT=#109#0%222.222.222.222%22%USER%%-1%-1% %%22%%0%-1%Interactive shell%
SEGMENT=#109#0%333.333.333.333%22%USER%%-1%-1% %%22%%0%-1%Interactive shell%
SEGMENT=#109#0%444.444.444.444%22%USER%%-1%-1% %%22%%0%-1%Interactive shell%
SEGMENT=#109#0%555.555.555.555%22%USER%%-1%-1% %%22%%0%-1%Interactive shell%

Advertisement

Answer

You aren’t escaping your { and } with as you should, also you probably want to use -o for “only show match”

grep -o --regexp="[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}" sessions
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement