Grep an IP with exact match and match between random string

Simplify and be more explicit.

$: grep '[^.0-9]1.1.1.1[^.0-9]' txt
1. IP [1.1.1.1]
4. IP "1.1.1.1 "
7. IP U*@K1.1.1.1-I([email protected]

This is still flawed, though – add another record to your test data.

$: grep '[^.0-9]1.1.1.1[^.0-9]' txt
1. IP [1.1.1.1]
4. IP "1.1.1.1 "
7. IP U*@K1.1.1.1-I([email protected]
11. IP [1a1b1c1]

Then try this:

$: grep '[^.0-9]1\.1\.1\.1[^.0-9]' txt
1. IP [1.1.1.1]
4. IP "1.1.1.1 "
7. IP U*@K1.1.1.1-I([email protected]

This still doesn’t account for the possibility of the IP at the very ends of the line, so if that’s a possibility at all,

$: grep -E '(^|[^.0-9])1\.1\.1\.1([^.0-9]|$)' txt
1. IP [1.1.1.1]
4. IP "1.1.1.1 "
7. IP U*@K1.1.1.1-I([email protected]
12. IP 1.1.1.1

If IP comes in as a variable, you can quote it in place.

$: ip=1.1.1.1
$: echo "grep -E '(^|[^.0-9])${ip//./\\.}([^.0-9]|$)'"
grep -E '(^|[^.0-9])1\.1\.1\.1([^.0-9]|$)'
$: grep -E "(^|[^.0-9])${ip//./\\.}([^.0-9]|$)" txt
1. IP [1.1.1.1]
4. IP "1.1.1.1 "
7. IP U*@K1.1.1.1-I([email protected]
12. IP 1.1.1.1

This can be problematic if your patterns get complex, but works fine here.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top