r/openbsd • • Nov 12 '22

possible bug with a simple Regular Expression using grep -E

So was trying to use grep to find IP addresses having the form nn.nn.nn.nnn (with a leading space), with my OpenBSD box running version 6.6.

command:

cat text.txt | grep -E '\s([0-9]{2}.){3}[0-9]{1,3}'

text file text.txt:

" 12.34.56.255"

OpenBSD wasn't able to find it but my Linode virtual machine running Debian found it.

Does anyone know if this was a known bug with grep and has since been fixed?

0 Upvotes

10 comments sorted by

17

u/kevans91 Nov 12 '22

\s is a GNU extension; try [[:space:]] (POSIX-specified) instead.

2

u/Weird_Childhood8585 Nov 12 '22

That was it. Thanks!

5

u/Marc_MK Nov 12 '22

Also you dont need to cat. You can just grep files directly.

1

u/Weird_Childhood8585 Nov 12 '22 edited Nov 12 '22

Thanks, I know... but that was just an example. It was part of a longer pipe sequence originally. I should have avoided the text file by using echo to demonstrate the regex failure...

echo " 12.34.56.123" | grep -E '\s([0-9]{2}.){3}[0-9]{1,3}'

5

u/danstermeister Nov 12 '22

That realization dawning in me was one of the more embarrassing parts of my Unix career.

3

u/I_Am_Jacks_____ Nov 12 '22

When you're testing something, sometimes it makes sense to "cat foo | grep bar" because it's easier to up-arrow and edit "bar" than up-arrow, cursor back over "foo" to edit "bar". Especially when "foo" is /nfs/mount/server1/local/path/to/some/file/you/are/grepping

4

u/john-witty-suffix Nov 12 '22

Also, and this is just for future reference since this is already working for you (although it may not in subtle ways with different data inputs): you want to escape the dot, since that's actually matching "any character", and not a literal . like you probably want:

'[[:space:]]([0-9]{2}\.){3}[0-9]{1,3}'

It's the backslash before the dot I'm talking about...that tells the regex engine to treat that as a literal . and not as the "any character" special character.

1

u/Weird_Childhood8585 Nov 12 '22

I think you only need the escape character if you don't use -E. It works fine how it is. Thanks though.

3

u/john-witty-suffix Nov 12 '22

The fact that you think it doesn't make it true.

The expression you have is a good approximation because a literal . is matched by the expression "any character". Given how "tight" the rest of the regex is for matching IP addresses, it probably won't become a practical problem though.

You can see the difference by adding this string to your list of input lines:

 12,34X56 255

1

u/Weird_Childhood8585 Nov 13 '22

You're right. I stand corrected. I should have escaped the .