Perl在"-0"模式下匹配换行符 [英] Perl match newline in `-0` mode
问题描述
假设我有一个像这样的文件:
Suppose I have a file like this:
I've got a loverly bunch of coconut trees.
Newlines!
Bahahaha
Newlines!
the end.
我想替换出现的换行符"!用(例如)NEWLINES!包围着空白行.因此,理想的输出是:
I'd like to replace an occurence of "Newlines!" that is surrounded by blank lines with (say) NEWLINES!. So, ideal output is:
I've got a loverly bunch of coconut trees.
NEWLINES!
Bahahaha
Newlines!
the end.
尝试
忽略用换行符包围",我可以这样做:
Attempts
Ignoring "surrounded by newlines", I can do:
perl -p -e 's@Newlines!@NEWLINES!@g' input.txt
替换所有出现的换行符!"并带有"NEWLINES!".
Which replaces all occurences of "Newlines!" with "NEWLINES!".
现在,我尝试仅选择换行符"!被\ n包围:
Now I try to pick out only the "Newlines!" surrounded with \n:
perl -p -e 's@\nNewlines!\n@\nNEWLINES!\n@g' input.txt
没有运气(请注意-我不需要s
开关,因为我没有使用.
,并且我不需要m
开关,因为我没有使用^
和
No luck (note - I don't need the s
switch because I'm not using .
and I don't need the m
switch because I'm not using ^
and $
; regardless, adding them doesn't make this work). Lookaheads/behinds don't work either:
perl -p -e 's@(?<=\n)Newlines!(?=\n)@NEWLINES!@g' input.txt
经过一些搜索,我发现perl
逐行读取文件(很有意义; sed
也是).因此,我使用-0
开关:
After a bit of searching, I see that perl
reads in the file line-by-line (makes sense; sed
does too). So, I use the -0
switch:
perl -0p -e 's@(?<=\n)Newlines!(?=\n)@NEWLINES!@g' input.txt
当然这是行不通的--0
用空字符替换换行字符.
Of course this doesn't work -- -0
replaces new line characters with the null character.
所以我的问题是-我该如何匹配该模式(我不希望在regex的"s @ pattern @ replacement @ flags"结构之外编写任何Perl)?
So my question is -- how can I match this pattern (I'd prefer not to write any perl beyond the regex 's@pattern@replacement@flags' construct)?
是否可以匹配此空字符?我确实尝试过:
Is it possible to match this null character? I did try:
perl -0p -e 's@(?<=\0)Newlines!(?=\0)@NEWLINES!@g' input.txt
无效.
谁能告诉我如何在perl中匹配换行符?是否处于-0
模式?还是应该使用awk
之类的东西? (我从sed
开始,但是即使使用-r
,它似乎也没有超前/落后的支持.之所以选择perl是因为我对awk一点都不熟悉.)
Can anyone tell me how to match newlines in perl? Whether in -0
mode or not? Or should I use something like awk
? (I started with sed
but it doesn't seem to have lookahead/behind support even with -r
. I went to perl because I'm not at all familiar with awk).
欢呼.
(PS:此问题不是我想要的,因为他们的问题与.+
匹配的换行符有关.
(PS: this question is not what I'm after because their problem had to do with a .+
matching newline).
推荐答案
以下内容应该对您有用:
Following should work for you:
perl -0pe 's@(?<=\n\n)Newlines!(?=\n\n)@NEWLINES!@g'
这篇关于Perl在"-0"模式下匹配换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!