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

syntax:
script.pl maxnumberofmatches pattern
example:
script.pl 100 /^foo\d\d-...?-\d\d(foo2|foo3)[^\\]+foo4$/

I have a textfile with a number of lines, and I would like that each line that matches the pattern is saved to another textfile (up to maxnumberofmatches lines).

Is this possible at all (or can pattern only contain word characters and not meta characters?), or would a totally different way to get closer to this problem be better?

Replies are listed 'Best First'.
Re: (How) can I use regex patterns to find matching lines in a textfile?
by jmcnamara (Monsignor) on Nov 20, 2002 at 12:10 UTC

    Here is one way:     perl -ne 'print if /pattern/ and $i++ < 100' file

    And here is another:     grep pattern file | head -100

    --
    John.

      I am using WinXP... with perl -ne 'print if /pattern/ and $i++ < 100 ' myfile.txt I just get a message "The file can't be found" :( Ritter

        Windows requires double quotes. This should work:     perl -ne "print if /pattern/ and $i++ < 100" file.txt

        --
        John.

Re: (How) can I use regex patterns to find matching lines in a textfile?
by aging acolyte (Pilgrim) on Nov 20, 2002 at 12:12 UTC
    Ritter, if you are using unix you might want to consider using grep
    system ("grep pattern | head -maxnumberofmacthes");
    AA
Re: (How) can I use regex patterns to find matching lines in a textfile?
by husoft (Monk) on Nov 20, 2002 at 12:24 UTC
    yet another way to do this.
    script.pl maxnumofmatches word-to-find
    #!/usr/bin/perl my $x=0;open(OF, ">OUT.txt");open(IF, "<IN.txt"); while(<IF>){if(/$ARGV[1]/){print OF "$_" if $x < $ARGV[0];$x++}} close IF;close OF;
      husoft, but "word-to-find" can't contain metacharacters like in the example I posted first, can it? Ritter
        You have to type only the word you want to find.
        If you want to be able to make it like the example you posted (with metachars).
        then replace /$ARGV[1]/ for eval($ARGV[1]).