简体   繁体   English

Perl单行代码中的跨行正则表达式匹配

[英]Cross-line regex match in a Perl one-liner

My question sounds trivial, but I google many page still can't not find an answer. 我的问题听起来很琐碎,但我在Google的许多页面上仍然找不到答案。

I am on Windows. 我在Windows上。 I have a text file. 我有一个文本文件。 If I open it with Notepad++, it looks like this 如果我用记事本++打开它,它看起来像这样

在此处输入图片说明

I want to try several things 我想尝试几件事

  1. delete all carriage return and line feed 删除所有回车和换行

    perl -i.bak -pe "s/\\r\\n//g" a.txt

surprisingly, there is nothing changed. 令人惊讶的是,没有任何改变。 What is wrong? 怎么了? But according to the doc , I am pretty sure \\r is CR and \\n is LF 但是根据文档 ,我很确定\\rCR\\nLF

  1. What I actually want to do is match across line. 我真正想做的是跨线比赛。 for example ^function.*\\r\\n! 例如^function.*\\r\\n! will match just like Notepad++ will does 会像Notepad ++一样匹配

在此处输入图片说明

If we want to indent the ! 如果我们要缩进! line if its previous line is started with "function", a naive thought would be (actually it works is notepad++) 如果它的前一行以“功能”开头,则天真的想法是这样(实际上它是notepad ++)

perl -i.bak -pe "s/^(function.*\r\n)!/$1\t!/g" a.txt

But it didn't work. 但这没有用。 How to do it correctly? 如何正确做?

By default, on Windows, CR+LF gets transformed to LF on read, and LF gets transformed to CR+LF on write. 默认情况下,在Windows上,CR + LF在读取时转换为LF,LF在写入时转换为CR + LF。 This makes lines look like they're LF-terminated regardless of the OS. 这使行看起来像是LF终止的,而与操作系统无关。


If sounds like you want to add a leading tab to lines starting with ! 如果听起来像您想在以!开头的行中添加前导制表符! .

perl -i.bak -pe"s/^!/\t!/" a.txt
   -or-
perl -i.bak -pe"s/^(?=!)/\t/" a.txt

You might also be trying to avoid doing it on the first line. 您可能还试图避免在第一行上执行此操作。

perl -i.bak -pe"s/^!/\t!/ if $. > 1" a.txt
   -or-
perl -i.bak -pe"s/^(?=!)/\t/ if $. > 1" a.txt
  1. perl -i.bak -pe "s/\\n//" a.txt

Ie just change \\r\\n to \\n for the \\r\\n is automatically converted to \\n on Windows as it was explained by ikegami. 即只需更改\\r\\n\\n\\r\\n将自动转换\\n在Windows,因为它是由池上解释。


  1. perl -i.bak -0777 -pe "s/^(function.*?\\n)!/\\1\\t!/gm" a.txt

The main point here is that you need to read the entire file contents into a single string in order to do cross-line matches. 这里的要点是,您需要将整个文件内容读入单个字符串中才能进行跨行匹配。 -0777 parameter instructs Perl to do so (alternatively you may set $/ to an empty string from within Perl script). -0777参数指示Perl这样做(或者,您可以在Perl脚本中将$/设置$/空字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM