grep 的参数列表太长

grep 的参数列表太长

通常,要在选定的文件中搜索并替换字符串,我会使用以下方法查找:

grep -rl 'pattern' .

除非您有大量匹配项,否则这种方法很有效。

无论如何,我环顾四周,发现了一个建议find

find /root/path -type f -exec grep -l 'FIND' {} +

这工作正常,但是当我尝试将它传递到 Perl 中进行替换时,仍然出现错误:

perl -p -i -e 's|FIND|REPLACE|g' `find /root/path -type f -exec grep -l 'FIND' {} +`

-bash: /usr/local/bin/perl: Argument list too long

有没有办法解决?

答案1

正如人们所建议的,我需要编写一个小脚本来为我创造奇迹:)

对我来说,我有很多文件 - 因此为了加快速度(并使find服务器更好一些),我将我的文件拆分为多个进程以处理较大的文件夹。因此脚本是:

#!/usr/bin/perl

my $find = q|string-to-find|;
my $replace = q|replace-with|;

my @paths = split /\n/, q|/home/user/folder1
/home/user/folder2
/home/user/folder3
/home/user/folder4|;

my $debug = 1;

foreach my $path (@paths) {
    my @files = split /\n/, `find $path -type f -exec grep -l '$find' {} +`;

    foreach (@files) {
        chomp;
        if (-f $_) {
            print qq|Doing $_\n| if $debug > 0;
            `sed -i 's/$find/$replace/g' $_`
        }

    }

}

然后只需从 SSH 运行它:

perl script-name.cgi

相关内容