多行搜索替换为 Perl [英] Multiline search replace with Perl
问题描述
我知道这种问题以前已经被问过很多次了.再次来到这里的原因是我觉得我错过了一些简单而基本的东西.
I know this kind of questions have been asked already many times before. The reason why I come here again is that I feel like I've missed something simple and fundamental.
是否可以将这种搜索替换例程做得更好.例如,无需两次打开同一个文件.也欢迎速度相关的建议.
Is it possible to make this kind of search-replace routine better. For example without opening same file twice. Also speed related advices are welcome.
请注意,这适用于多行匹配并替换多行字符串.
Please notice that this works with multiline matches and replaces also multiline strings.
#!/bin/perl -w -0777
local $/ = undef;
open INFILE, $full_file_path or die "Could not open file. $!";
$string = <INFILE>;
close INFILE;
$string =~ s/START.*STOP/$replace_string/sm;
open OUTFILE, ">", $full_file_path or die "Could not open file. $!";
print OUTFILE ($string);
close OUTFILE;
推荐答案
这种查找和替换可以用单行比如 -
This kind of search and replace can be accomplished with a one-liner such as -
perl -i -pe 's/START.*STOP/replace_string/g' file_to_change
有关完成同一件事的更多方法,请查看此线程.要处理多行搜索,请使用以下命令 -
For more ways to accomplish the same thing check out this thread. To handle multi-line searches use the following command -
perl -i -pe 'BEGIN{undef $/;} s/START.*STOP/replace_string/smg' file_to_change
为了将以下代码从单行代码转换为 perl 程序,请查看 perlrun文档.
In order to convert the following code from a one-liner to a perl program have a look at the perlrun documentation.
如果你真的发现需要将它转换成一个工作程序,那么就让 Perl 为你处理文件的打开/关闭.
If you really find the need to convert this into a working program then just let Perl handle the file opening/closing for you.
#!/usr/bin/perl -pi
#multi-line in place substitute - subs.pl
use strict;
use warnings;
BEGIN {undef $/;}
s/START.*STOP/replace_string/smg;
然后您可以使用文件名作为第一个参数调用脚本
You can then call the script with the filename as the first argument
$perl subs.pl file_to_change
如果你想要一个更详细的脚本来处理文件打开/关闭操作(我们不是喜欢所有那些死"语句)然后看看 perlrun 中的示例 -i[extension]切换.
If you want a more meatier script where you get to handle the file open/close operations(don't we love all those 'die' statements) then have a look at the example in perlrun under the -i[extension] switch.
这篇关于多行搜索替换为 Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!