Reputation: 488
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%
Upvotes: 3
Views: 998
Reputation: 488
The issue was that I was not escaping the curly braces, thanks @Victory! Once I did that, it all worked. Additionally, splitting the fields by "%" also worked remarkably well, again, thanks @Filipe Goncalves
Upvotes: 0
Reputation: 2931
I would use
egrep '0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.0*([0-9]{1,2}|1[0-9]{2}|2[0-4][0-9]|25[0-5])' sessions
to ensure that ip-like entries won't match my regexp.
Upvotes: 0
Reputation: 21213
As mentioned in other answers, you need to escape {
and }
.
Alternatively, given your input format, this is in my opinion simpler and easier to read:
awk -F'%' '{ print $2 }' sessions
It works by splitting each line around the %
character and selecting the 2nd field.
Upvotes: 1
Reputation: 5890
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
Upvotes: 1