我怎样才能让一个批处理文件来像使用Perl的简单grep的行动呢? [英] How can I make a batch file to act like a simple grep using Perl?
问题描述
我已经知道答案显然对这个问题:刚才下载<插入喜爱的Windows grep或者在这里与GT类似grep的工具;。不过,我在一个环境由当地IT人员的工作与严格的控制,以我们允许哪些会对我们的电脑。我只想说:我有机会获得Perl的Windows XP上。这是我想出了一个快速的Perl脚本我想要做什么,但我还没有想通了如何建立一个批处理文件,这样我既可以管一个命令的输出到它,或者通过一个文件(或文件列表?)作为后一个说法前pression到grep
I already know the obvious answer to this question: "just download <insert favorite windows grep or grep-like tool here>". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep":
perl -n -e "print $_ if (m![expression]!);" [filename]
我怎样写一个批处理脚本,我可以做这样的事情,例如:
How do I write a batch script that I can do something like, for example:
dir | grep.bat mypattern
grep.bat mypattern myfile.txt
修改:虽然我标志着另一个答案,我想给荣誉给<一个href=\"http://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099\">Ray海耶斯回答,因为它是真正的Windows操作方式来做到这一点,即使另一个答案是技术上更接近我想要的东西。
EDIT: Even though I marked another "answer", I wanted to give kudos to Ray Hayes answer, as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.
推荐答案
我写这一段时间回来:
@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
这篇关于我怎样才能让一个批处理文件来像使用Perl的简单grep的行动呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!