本文介绍了一线可打印两个图案之间的所有线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用一行Perl代码,最简单的方法是打印两个模式之间的所有行(不包括带有模式的行)吗?

Using one line of Perl code, what is the shortest way possible to print all the lines between two patterns not including the lines with the patterns?

如果这是file.txt:

If this is file.txt:

aaa
START
bbb
ccc
ddd
END
eee
fff

我要打印此:

bbb
ccc
ddd

我可以使用以下方法获得大部分信息:

I can get most of the way there using something like this:

perl -ne 'print if (/^START/../^END/);'

不过,其中包括STARTEND行.

我可以像这样完成工作:

I can get the job done like this:

perl -ne 'if (/^START/../^END/) { print unless (/^(START)|(END)/); };' file.txt

但这似乎是多余的.

我真正想做的是使用像这样的lookbehind和lookahead断言:

What I'd really like to do is use lookbehind and lookahead assertions like this:

perl -ne 'print if (/^(?<=START)/../(?=END)/);' file.txt

但这是行不通的,我认为我的正则表达式有些错误.

But that doesn't work and I think I've got something just a little bit wrong in my regex.

这些只是我尝试过的一些不产生任何输出的变体:

These are just some of the variations I've tried that produce no output:

perl -ne 'print if (/^(?<=START)/../^.*$(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../^.*(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../.*(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../^.*(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../$(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../^(?=END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../(?=^END)/);' file.txt
perl -ne 'print if (/^(?<=START)/../.*(?=END)/s);' file.txt

推荐答案

读取整个文件,进行匹配并打印.

Read the whole file, match, and print.

perl -0777 -e 'print <> =~ /START.*?\n(.*?)END.*?/gs;' file.txt

如果单独在线,可能会在START|END之后下降.*?.然后将\n放到各段之间的空白行.

May drop .*? after START|END if alone on line.Then drop \n for a blank line between segments.

读取文件,用START|END分隔行,打印@F的所有奇数

Read file, split line by START|END, print every odd of @F

perl -0777 -F"START|END" -ane 'print @F[ grep { $_ & 1 } (0..$#F) ]' file.txt


使用END { }块进行额外的处理.将}{用于END { }.


Use END { } block for extra processing. Uses }{ for END { }.

perl -ne 'push @r, $_ if (/^START/../^END/); }{ print "@r[1..$#r-1]"' file.txt

仅在文件中的单个此类段中起作用.

Works as it stands only for a single such segment in the file.

这篇关于一线可打印两个图案之间的所有线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:16