0

I'm trying to search a large list of IP address for a particular IP, but am getting false positives because of spaces. Please consider the following example:

$ a="192.168.1.1    192.168.1.2"
$ ip="1.1.192.168"

$ echo $a | grep "$ip"
192.168.1.1 192.168.1.2

Grep ignores the space and returns wrong results. How can I get grep to recognize that "1.1 192.168" is not equal to "1.1.192.168"?

3
  • 2
    grep does not ignore whitespace, . is a special grep operator which means "any character". Use grep -Fw "$ip" and go read grep's manpage.
    – user313992
    Apr 10, 2020 at 19:18
  • Your command is returning anything that matches any of 192.168.1.2. 1, 2, 6, 8, 9, 192, 168, and . (any character) all have matches in the output from the echo command. If you just want it to return. If you want to look for that exact string, then as mosvy said, you need to use grep -F or grep -w. Apr 10, 2020 at 19:24
  • No, it matches 1<any char>1<any char>192<any char>168 and echo $a contains 1.1 192.168. The output of echo $a is different from echo "$a".
    – Freddy
    Apr 10, 2020 at 19:45

1 Answer 1

2

Get used to quoting your variables. You don't find a match after

echo "$a" | grep "$ip"

This is not a general solution, next time there might be just one space between the IPs. Use

ip="1[.]1[.]192[.]168"

Still problems, you might match 101.1.192.168.
So try the -Fw options

i.e. echo "$a" | grep -Fw "$ip"

5
  • 1
    @NasirRiley saying the same wrong thing twice doesn't make it right
    – roaima
    Apr 10, 2020 at 20:01
  • @WalterA That is correct. $a absolutely does need to be quoted and I wasn't suggesting that it doesn't. I was referring to $ip, as you correctly surmised. Apr 11, 2020 at 15:34
  • Yes I agree, quotes on the $ip don't matter. Were you suggesting removing them. Why? I am going to tidy this comment thread, as it is confusing and as we now see pointless. Apr 11, 2020 at 16:47
  • Above was a discussion that is solved now. I have deleted my comments, trying to keep only relevant comments.
    – Walter A
    Apr 11, 2020 at 17:06
  • @ctrl-alt-delor I wasn't suggesting removing them but was only stating that they weren't needed. I have deleted my previous comments and just left the last one so that it is clear that I was stating that $ip doesn't need to be quoted and not $a.. Apr 11, 2020 at 18:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .