http://www.perlmonks.org?node_id=1016422

Tommy has asked for the wisdom of the Perl Monks concerning the following question:

Are you forced to use a system grep without perl-compatible regex support? (i.e.- no "-P")

Let's say you want to grep a file for "foo", but not if it's proceeded by a comment "#" (with possible, legal leading whitespace). How would you grep for that on Unix with it's lame grep?

I turn to Perl. Can it be done without perl in one grep? Can this be done in Perl, but more simply? Show me!

Meanwhile, at the shell...

[[ "$( cat filename | perl -e 'print for grep { /^[[:space:]]{0,}#.+?f +oo/ } <>' )" != "" ]] && found_but_commented=1;

I guess I'm looking for a re-usable perl-construct to use as a grep substitute. Something along those lines above. Is there anything more easy than | perl -e 'print for grep { /regex/ } <>


Tommy
A mistake can be valuable or costly, depending on how faithfully you pursue correction

Replies are listed 'Best First'.
Re: Grep'ping on Unix without perl-compatible gnu grep - can you do it better?
by roboticus (Chancellor) on Feb 01, 2013 at 02:31 UTC

    Tommy:

    I'd do it like this:

    $ grep -E '^[^#]*foo' boom now is the foo for all $ cat boom now is the foo for all now # foo is the blarg

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      Indeed, the -E switch (aka egrep) does activate a modern regexp syntax, and is found in a boatload more systems than where -P is. It does not come with all the Perl features, but it is way more comfortable than the basic 1980s dialect grep & co default to.
        You could (have) try(ied) awk on systems that has(had) a lacking grep.
Re: Grep'ping on Unix without perl-compatible gnu grep - can you do it better?
by kielstirling (Scribe) on Feb 01, 2013 at 02:35 UTC
    perl -ne 'print if !/^#/ and /foo/' /tmp/foo.txt
    is that what you want? Or using the regex for the above post
    perl -ne 'print if /^[^#]*foo/' /tmp/foo.txt

      Very nice...except you still have to account for potential preceeding whitespace before the hashmark /^[[:space:]]{0,}#/

      Tommy
      A mistake can be valuable or costly, depending on how faithfully you pursue correction
Re: Grep'ping on Unix without perl-compatible gnu grep - can you do it better?
by Tux (Canon) on Feb 01, 2013 at 07:37 UTC

    Install App::Ack ?


    Enjoy, Have FUN! H.Merijn