Search code examples
regexmacosawklsof

Strange behavior using lsof and awk together in Mac terminal?


I want to find all of the lines in lsof with "Google" in them, so I tried the following:

lsof |  awk '/.*google.*/ { print $1 "," $2 "," $3} ' > new_file.csv

which yields correctly an output with rows starting with the word "google".

But, then I try this and the csv contains nothing:

lsof |  awk '/\s*google.*/ { print $1 "," $2 "," $3} ' > new_file.csv

But, I thought that the \s* means any number of spaces. Is there any reason for this behavior? Thank you.


Solution

  • \s does mean spaces and \s* does mean zero-or-more spaces but not in awk.

    awk uses a different (older) regex engine.

    For awk you want [[:space:]]* to match zero-or-more spaces. (That's a character class class of [:space:] in a character list [].)

    That being said if you just care about google being in the output then you just need /google/.

    If you want an word-anchored google then you want /\<google\>/.

    As Ed Morton points out GNU Awk version 4.0+ added support for the \s metacharacter as well.