Search code examples
regexgrepwhitespaceslash

How to grep for non-whitespaces adjacent to slashes


I want to grep for comments without a space after them...

The following grep expression does not work to extract //abc patterns, but I'm not sure why...

echo "//asdf" | grep '//^[ ]*' Should return //asdf, whereas

echo "// asdf" | grep '//^[ ]*' should return nothing at all.

To conclude, the above grep statement is broken somehow, but it appears that the expression above is saying "two slashes adjacent to a non- whitespace".

  • What is the proper way to grep for "two slashes adjacent to a whitespace"?
  • Concretely, how should i modify '//^[ ]*' to match the following expressions: //a, //asdfasdf, //1234, //another one 1234.

Solution

  • This is because the negation ^ has to be placed inside the [ ] block:

    $ echo "//asdf" | grep '//[^ ]'
    //asdf
    $ echo "// asdf" | grep '//[^ ]'
    
    

    That is, use [^ ] instead of ^[ ]. This way, saying [^ ] you match a single character not present in the list.

    Whereas when you were saying ^\[ \] you were saying:

    • ^ assert position at start of the string
    • [ ] match a single character present in the list below