Pergunta

Eu já sei a resposta óbvia a esta pergunta: "Basta fazer o download ". No entanto, eu trabalho em um ambiente com controles estritos pela equipe de TI local, como o que estamos autorizados a ter em nossos computadores. Basta dizer: Eu tenho acesso a Perl no Windows XP. Aqui está uma rápida script Perl que eu vim com que faz o que eu quero, mas eu ainda não descobri se como configurar um arquivo de lote de tal forma que eu pode canalizar uma saída de comando para ele, ou passar um arquivo (ou lista de arquivos ?) como um argumento após a "expressão a grep":

perl -n -e "print $_ if (m![expression]!);" [filename]

Como faço para escrever um script em lotes que posso fazer algo como, por exemplo:

dir | grep.bat mypattern
grep.bat mypattern myfile.txt

Editar : Mesmo que eu marcada outra "resposta", eu queria dar parabéns a Ray Hayes resposta , pois é realmente o "Caminho Windows" para fazê-lo, é tecnicamente mais perto do que eu queria.

Foi útil?

Solução

Eu escrevi este um tempo atrás:

@rem = '--*-Perl-*--
@echo off
perl -x -S %0 %*
goto endofperl


@rem -- BEGIN PERL -- ';
#!d:/Perl/bin/perl.exe -w
#line 10
use strict; 
#use Test::Setup;
use Getopt::Long;

Getopt::Long::Configure ("bundling");

my $ignore_case    = 0;
my $number_line    = 0;
my $invert_results = 0;
my $verbose        = 0;

my $result = GetOptions( 
    'i|ignore_case' => \$ignore_case, 
    'n|number'      => \$number_line,
    'v|invert'      => \$invert_results,
    'verbose'       => \$verbose,
);
my $regex = shift;

if ( $ignore_case ) { 
    $regex = "(?i:$regex)";
}
$regex = qr/$regex/;
print "\$regex=$regex\n";
if ( $verbose ) { 
    print "Verbose: Ignoring case.\n"                      if $ignore_case;
    print "Verbose: Printing file name and line number.\n" if $number_line;
    print "Verbose: Inverting result set.\n"               if $invert_results;
    print "\n";
}

@ARGV = map { glob "$_" } @ARGV;

while ( <> ) { 
    my $matches = m/$regex/;
    next unless $matches ^ $invert_results;
    print "$ARGV\:$.:" if $number_line;
    print;
}

__END__
:endofperl

Outras dicas

A maioria do poder de grep já está disponível em sua máquina na aplicação do Windows Findstr.exe que faz parte de todos, máquinas Windows 2000 XP e Vista! Ele oferece RegExpr etc.

Muito mais fácil do que um arquivo de lote que por sua vez chama Perl!

c:\>FindStr /?    
Searches for strings in files.

FINDSTR [/B] [/E] [/L] [/R] [/S] [/I] [/X] [/V] [/N] [/M] [/O] [/P] [/F:file]
        [/C:string] [/G:file] [/D:dir list] [/A:color attributes] [/OFF[LINE]]
        strings [[drive:][path]filename[ ...]]

  /B         Matches pattern if at the beginning of a line.
  /E         Matches pattern if at the end of a line.
  /L         Uses search strings literally.
  /R         Uses search strings as regular expressions.
  /S         Searches for matching files in the current directory and all
             subdirectories.
  /I         Specifies that the search is not to be case-sensitive.
  /X         Prints lines that match exactly.
  /V         Prints only lines that do not contain a match.
  /N         Prints the line number before each line that matches.
  /M         Prints only the filename if a file contains a match.
  /O         Prints character offset before each matching line.
  /P         Skip files with non-printable characters.
  /OFF[LINE] Do not skip files with offline attribute set.
  /A:attr    Specifies color attribute with two hex digits. See "color /?"
  /F:file    Reads file list from the specified file(/ stands for console).
  /C:string  Uses specified string as a literal search string.
  /G:file    Gets search strings from the specified file(/ stands for console).
  /D:dir     Search a semicolon delimited list of directories
  strings    Text to be searched for.
  [drive:][path]filename
             Specifies a file or files to search.

Use spaces to separate multiple search strings unless the argument is prefixed
with /C.  For example, 'FINDSTR "hello there" x.y' searches for "hello" or
"there" in file x.y.  'FINDSTR /C:"hello there" x.y' searches for
"hello there" in file x.y.

Regular expression quick reference:
  .        Wildcard: any character
  *        Repeat: zero or more occurances of previous character or class
  ^        Line position: beginning of line
  $        Line position: end of line
  [class]  Character class: any one character in set
  [^class] Inverse class: any one character not in set
  [x-y]    Range: any characters within the specified range
  \x       Escape: literal use of metacharacter x
  \<xyz    Word position: beginning of word
  xyz\>    Word position: end of word

Baixe e instale ack . É um substituto superior ao grep e - graças a magia de modo dual .BAT mágica roteiro de Perl / Perl -. Ele vai trabalhar na linha de comando para você

Em primeiro lugar, transformá-lo em um script real em vez de uma frase:

use strict;
use warnings;

my $pattern = shift or die "Usage: $0 <pattern> [files|-]\n";
while (<>) { print if /$pattern/ }

Em seguida, transformá-lo em um arquivo de lote usando pl2bat:

pl2bat mygrep.pl

Isto irá criar "mygrep.bat".

Para um grep full-featured (e muitas outras aplicações Unix) escrito completamente em Perl, consulte a Perl Power Tools projeto.

Enquanto as ferramentas de Perl de energia são bons, se você só pode executar Perl, eu geralmente preferem o conjunto de GnuWin32 ferramentas. Eles não necessitam de instalação. (Você não precisa de privilégios administrativos, apenas um diretório que você pode escrever para.)

Eu concordo com Axeman e Hayes sobre o uso de uma ferramenta melhor para o trabalho. Dito isto, você poderia tentar algo como isto em seu arquivo de lote para executar o seu script personalizado contra uma expressão de arquivo curinga:

@echo off

for /f "usebackq delims==" %%f in (`dir /w /b %2`) do (
    perl -n -e "print $_ if (m!%1!);" "%%f"
    REM or something like:  myperlscript.pl %1 "%%f"
)

Desta forma, você pode fazer coisas como "grep mypattern myfile.txt", "grep mypattern.", "Grep mypattern * .doc", etc.

Você precisa fazer algo como isto:

@echo off
perl -x -S script.pl %1

O "% 1" vai passar o argumento para o script Perl. Guardá-lo como um arquivo .bat, e você está pronto para ir.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top