多行搜索替换为Perl [英] Multiline search replace with Perl

查看:96
本文介绍了多行搜索替换为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;

推荐答案

可以使用诸如-

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

如果您想要一个更丰富的脚本来处理文件打开/关闭操作(我们不喜欢所有那些"die"语句),那么请在-i [extension]下查看perlrun中的示例切换.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆