Unable to grep using wildcard in a file.

I wish to check if my file has a line that does not start with '#' and has

  1. Listen and 2. 443
 echo "Listen               443" > test.out

grep 'Listen *443' test.out | grep -v '#'
Listen               443

The above worked fine but when the entry changes to the below the grep fails when i dont want it to fail.

echo "Listen     192.888.22.111:443" > test.out

Also, i do grep -v '#' to ignore lines having # i.e comments but is there a way to check if # is the starting (not necessary the first character considering there are whitespaces before the #) charecter in the line only then it should be ignored else be considered by the grep query.

So....

should not be considered

But

should be considered.

Would this do?

grep  '^[^#]*Listen.*[^0-9]443\([^0-9]\|$\)' file

The problem is that your expression is matching Listen followed by any number of spaces then 443 . Your definition is explicit in being for 'any number of spaces' with the * sequence.

Do you really mean "Match records that start with Listen and end with :443 # " ? That would be grep "^Listen.*:443 #$" or you could be more explicit and say that it would have to match an IP address structure with "^Listen.*([0-9]{1,3}\.){3}[0-9]{1,3}:443 #$"

To explain a little more:-

^                             - Start of line
Listen                        - Liternal text, exactly as it is.
.*                            - zero or more of any character
([0-9]{1,3}\.){3}             - exactly 3 of the bracketed bit (see line below and sub-note below)
[0-9]{1,3}                    - between 1 & 3 characters between 0 and 9 inclusive
:443 #                        - Literal text, exactly as it is.
$                             - End of line, important to avoid false matches that don't end at the end of your search..

So to expand more on ([0-9]{1,3}\.){3} the braces {3} mean three of the previous thing. In this case the thing is ([0-9]{1,3}\.) which is between 1 & 3 digits followed by an explicit dot/full stop. You have to use \. because the dot is special as you have in the .* which means any number of any character.

If the line might not start with Listen then you might just want to exclude a leading # , so you end up with the more complicated "^[^#]Listen.*([0-9]{1,3}\.){3}[0-9]{1,3}:443 #$" which is "Do not start with a hash. The [^#] means "Not this/these character(s)" which might be a bit confusing given it follows a ^ marking the start of the line. Of course if this might not be the first character, you might want to drop the first ^ anchoring it to the start of the line.

Does that help, or have I just confused things? :o

Robin

1 Like