in reply to grep command

And what if there are more than one occurances of "hello" in one line?
# perl -le'$cnt+=@{[m/\bhello\b/g]}for"aahello hello hello","bb heelo +hello phello";print$cnt' 3

or, on a file ...
# perl -nle'$cnt+=@{[m/\bhello\b/g]}}END{print$cnt' file

Enjoy, Have FUN! H.Merijn

Replies are listed 'Best First'.
Re^2: grep command
by ferreira (Chaplain) on Jan 18, 2007 at 14:01 UTC

    That's the simple modification I told about:

    $ perl -n -e '$count++ while /\bhello\b/g; END { print $count }' text. +out

    And to answer kyle at Re^2: grep command, my interpretation was that he was concerned about how many times the word happened with no concern for which particular lines. But then he tells about grepping — so if the issue is finding the lines and then telling how many times it appeared in total, this one may work:

      Almost!

      However, the last line in which "hello" is found is printed twice.

      CLI: perl -n -e "print, $count++ while /\bhello\b/g; END { print $count }" hello.out
              (quotes revised for windows)

      file hello.txt:
      hello. hellow, world. bye
      world says hello.
      bye
      hello, hellow, hello
      not now.
      done.

      output
      hello. hellow, world. bye
      world says hello.
      hello, hellow, hello
      hello, hellow, hello
      4

      I don't see it as a *simple* spoiler, as people quite often try it in scalar context like

      $cnt += m{pattern}g;

      which doesn't work as they expect.

      Enjoy, Have FUN! H.Merijn
        I don't see it as a *simple* spoiler, as people quite often try it in scalar context like
        $cnt += m{pattern}g;

        But then the usual workaround is

        $cnt += () = m{pattern}g;

        which is somewhat simpler and more natural than your reference-and-dereference trick.