perl - 有没有一种简单的方法来进行批量文件文本替换?

标签 perl search command-line replace bulk

我一直在尝试编写一个 Perl 脚本来替换我项目的所有源文件上的一些文本。我需要类似的东西:

perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" *.{cs,aspx,ascx}

但这会解析 全部 目录的文件 递归 .

我刚开始写一个脚本:
use File::Find::Rule;
use strict;

my @files = (File::Find::Rule->file()->name('*.cs','*.aspx','*.ascx')->in('.'));

foreach my $f (@files){
    if ($f =~ s/thisgoesout/thisgoesin/gi) {
           # In-place file editing, or something like that
    }
}

但现在我被困住了。有没有一种简单的方法可以使用 Perl 就地编辑所有文件?

请注意,我不需要保留每个修改过的文件的副本;我让他们都被颠覆了 =)

更新 : 我在 Cygwin 上试过这个,
perl -p -i.bak -e "s/thisgoesout/thisgoesin/gi" {*,*/*,*/*/*}.{cs,aspx,ascx

但看起来我的参数列表爆炸到了允许的最大大小。事实上,我在 Cygwin 上遇到了非常奇怪的错误......

最佳答案

如果您分配 @ARGV使用前 *ARGV (又名钻石 <>),$^I/-i将处理这些文件,而不是在命令行中指定的文件。

use File::Find::Rule;
use strict;

@ARGV = (File::Find::Rule->file()->name('*.cs', '*.aspx', '*.ascx')->in('.'));
$^I = '.bak';  # or set `-i` in the #! line or on the command-line

while (<>) {
    s/thisgoesout/thisgoesin/gi;
    print;
}

这应该完全符合您的要求。

如果您的模式可以跨越多行,请添加 undef $/;之前<>以便 Perl 一次对整个文件进行操作,而不是逐行操作。

关于perl - 有没有一种简单的方法来进行批量文件文本替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/248668/

相关文章:

php - 在自由格式文本中查找日期的最佳方法是什么?

string - 在 Perl 中将所有参数作为字符串传递给子例程

linux - 生成 Linux X11 事件?

regex - 为什么我在运行 Perl 单行程序时得到 "-bash: syntax error near unexpected token ` ('"?

java - 等于和包含有什么区别

xcode - Xcode "open quickly"和 Textmate "Go to file"使用什么样的搜索算法?

c++ - 解析命令行参数 c++ 时的奇怪行为

regex - 在大量字符串上测试 RegExp

php - 从 Laravel 命令中清除控制台

macos - 是否可以从命令行启动 Teamviewer 以接受连接?