in reply to Generating a grep command at run time

Do you actually need to generate a grep command or is it okay to actually perform the search with Perl itself?

Also, there is no reason to do cat file | grep pattern, you can just do grep pattern file. There is a small difference if you are searching more than one file, since grep pattern file1 file2 shows the file names on the output, whereas cat file1 file2 | grep pattern does not.

Okay, if you really need to generate a grep command, I would do it like this:

#!perl -w use strict; my $starttim = 4; my $endtime = 9; my $pattern = "^(" . join("|", map { sprintf "%02d", $_ } $starttim .. $endtime ) . ")"; my $cmd = "grep -e '$pattern' file"; print "cmd = $cmd\n";
The join function is great when you need to have things between the elements of list. Much easier than coding a loop.

Replies are listed 'Best First'.
Re: Re: Generating a grep command at run time
by runrig (Abbot) on May 22, 2003 at 17:21 UTC
    There is a small difference if you are searching more than one file, since grep pattern file1 file2 shows the file names on the output, ...
    Not if you use '-h'. Anyway, I would probably do the whole thing in perl, unless speed was really that much of an issue. And if it is (saving minutes or hours), then you might be able to do:
    perl -e ' # Generate pattern and file names... exec 'grep', '-e', $pattern, @files; ' [args...]