从Perl单行正则表达式中获取返回参数

时间:2013-02-20 14:44:49

标签: regex windows perl batch-file

如何从正则表达式Perl执行中返回匹配的值?

我想在我的批处理文件中进一步使用匹配。

批处理文件:

perl -p -e "ab{2}" c:\file.txt
REM echo %var% how can I get the result from perl?
REM do something with %var%

档案file.txt

abbreviation

更新zb22​​6:

test

Filename: dynamicFile.txt
Property: some property to neglect
Message: the message I want
Time: dynamicTime

3 个答案:

答案 0 :(得分:1)

您需要FOR命令:

@ECHO OFF
FOR /F "delims=" %%I IN ('perl -ne "print $1.\"\n\" if ~/(ab{2})/" c:\file.txt') DO SET match=%%I
ECHO match: %match%

请注意,这将返回最后一场比赛 - 这与您的示例regexp ab{2}无关,因为它始终会返回abb或没有。

修改1 :忘记在perl onliner中添加换行符 - 或者您可以使用Andrey的perl -pe ...版本,不需要打印换行符。

编辑2 :然后,安德烈的单行内容仅在行的开头匹配正则表达式,这不是您的问题所暗示的。正如您已经注意到的那样,它还会打印不匹配的行。我想不出perl -pe版本的简单修复......

编辑3 :这是您在评论中提供的其他信息的快速而肮脏的解决方案。

@ECHO OFF
FOR /F "usebackq delims=" %%I IN (`perl -e "local $/ = undef; open my $h, '<', $ARGV[0]; my $x = <$h>; print $1 if $x=~/Filename: dynamicFile.txt.*?Message: (.*?)Time/s;" c:\file.txt`) DO SET match=%%I
ECHO match: %match%

使用测试文件......

test

Filename: dynamicFile.txt
Property: some property to neglect
Message: the message I want
Time: dynamicTime
----
Filename: someOtherFile.txt
Property: some property to neglect
Message: someMessage
Time: dynamicTime

...这输出:

match: the message I want

答案 1 :(得分:0)

perl -p -e "s/^(ab{2}).*$/\1/" c:\file.txt

答案 2 :(得分:0)

perl -lne "print $1 if /(ab{2})/" C:\file.txt