本文介绍了Perl脚本与单行脚本-正则表达式在功能上的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个perl程序,该程序采用STDIN(从另一个bash命令通过管道传送). bash命令的输出非常大,大约200行.我想输入 entire 输入(多行),并将其输入到一个单行的perl脚本中,但是到目前为止,我尝试过的任何方法都没有起作用.相反,如果我使用以下perl(.pl文件):

I have a perl program that takes the STDIN (piped from another bash command). The output from the bash command is quite large, about 200 lines. I want to take the entire input (multiple lines) and feed that to a one-liner perl script, but so far nothing i've tried has worked. Conversely, if I use the following perl (.pl file):

#!/usr/bin/perl
use strict;

my $regex = qr/{(?:\n|.)*}(?:\n)/p;

if ( <> =~ /$regex/g ) {
  print "${^MATCH}\n";
}

并像这样执行我的bash命令:

And execute my bash command like this:

<bash command> | perl -0777 try_m_1.pl

有效.但作为单行代码,它不能与相同的regex/bash命令一起使用. print命令的结果为空.我已经这样尝试过了:

It works. But as a one-liner, it doesn't work with the same regex/bash command. The result of the print command is nothing. I've tried it like this:

<bash command> | perl -0777 -e '/{(?:\n|.)*}(?:\n)/pg && print "$^MATCH";'

和这个:

<bash command> | perl -0777 -e '/{(?:\n|.)*}(?:\n)/g; print "$1\n";'

还有很多其他事情,无法一一列举.我是perl的新手,只想使用它从文本中获取正则表达式输出.如果有什么比perl更好的方法(我从阅读中了解到该sed对此不起作用?),请随意提出建议.

And a bunch of other things, too many to list them all. I'm new to perl and only want to use it to get regex output from the text. If there's something better than perl to do this (I understand from reading around that sed wouldn't work for this?) feel free to suggest.

更新:基于@zdim答案,我尝试了以下有效的方法:

Update: based on @zdim answer, I tried the following, which worked:

<bash command> |  perl -0777 -ne '/(\{(?:\n|.)*\}(?:\n))/s and print "$1\n"'

我想我的正则表达式需要用()包起来,而{的花括号需要转义.

I guess my regex needed to be wrapped in () and the { curly braces needed to be escaped.

推荐答案

单线需要-n(或-p)来处理输入,以便打开文件,附加流并建立循环.即使 -0777 取消设置输入记录分隔符,因此可以立即读取文件;参见为什么使用-p | -n在perl一个衬管中以浆状模式使用?

A one-liner needs -n (or -p) to process input, so that files are opened, streams attached, and a loop set up. It still needs that even as the -0777 unsets the input record separator, so the file is read at once; see Why use the -p|-n in slurp mode in perl one liner?

该正则表达式与换行符或除换行符以外的任何字符匹配,并且有一个修饰符/s.也与之匹配换行符.然后,这需要放在花括号内,而您需要在新的Perls中进行转义.后面的换行不需要分组.

That regex matches either a newline or any character other than a newline, and there is a modifier for that, /s, with which . matches newline as well. Then that need be inside curly braces, which you need to escape in newer Perls. The newline that follows doesn't need grouping.

一共可以拥有

<bash command> | perl -0777 -ne'/(\{(.*)\}\n)/s and print "$1\n"'

这篇关于Perl脚本与单行脚本-正则表达式在功能上的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 14:36