Perl从目录中的文件替换字符串

时间:2014-05-26 05:33:10

标签: regex string perl file-io

我试图创建一个程序来替换目录中所有文件中的字符串。问题是我需要只在句子开头或结尾处或两者都改变​​它。这就是我到目前为止所做的:

use strict;
use warnings;
use File::Find;     #This lets us use the find() function, similar to 'find' in Unix 
                # -- which is especially helpful for searching recursively.

print "Which directory do you want to use?\n"; #Ask what directory to use
my $dir = readline STDIN;
chomp $dir; #Used for eliminating the newline character '\n'

print "What String would you like to search for?\n"; #Ask for what String to search for.
my $search = readline STDIN;
chomp $search;

print "What String would you like to replace it with?\n"; #Ask for what to replace it with.
my $replace = readline STDIN;
chomp $replace;

print "Would you like to replace $search if it is at the beginning of the sentence? (y/n) \n";
my $beg = readline STDIN;
chomp $beg;

print "Would you like to replace $search if it is at the end of the sentence? (y/n) \n";
my $end = readline STDIN;
chomp $end;


find(\&txtrep, $dir); #This function lets us loop through each file in the directory

sub txtrep  {
    if ( -f and /.txt$/) { # Proceeds only if it is a regular .txt file
        my $file = $_;  # Set the name of the file, using special Perl variable
        open (FILE , $file);
        my @lines = <FILE>; #Puts the file into an array and separates sentences
        my @lines2 = split(".", @lines);
        close FILE;

        if ($beg eq "y") {
            foreach my $slot (@lines2) {
                $slot =~ s/^$search/$replace/gi;
            }
        }

        if ($end eq "y") {
            foreach my $slot (@lines2) {
                $slot =~ s/$search$/$replace/gi;
            }
        }

        open (FILE, ">$file");
        print FILE @lines2;
        close FILE;
    }
}

运行之后,它只删除文件中的所有内容,而且我不知道语法是否适合更改字符串@句子的开头和结尾。请让我知道我做错了什么!谢谢!

2 个答案:

答案 0 :(得分:1)

我只想使用perl one-liner

perl -i.bak -pe&#39; s / ^ [search] / [replace] / g;&#39; [文件]表示行的开头 perl -i.bak -pe&#39; s / [search] $ / [replace] / g;&#39; [文件]为行尾

[search]和[replace]是占位符。

&#39; -i.bak&#39;将在替换之前备份文件。

快速谷歌搜索:perl one-liner search & repalce example

答案 1 :(得分:0)

您已启用use strict;,但使用变量@lines2时出现语法错误。

此外,您应该添加use autodie;,因为您正在进行文件处理。

以下内容可能是您正在搜索的内容:

my $data = do {
    open my $fh, $file;
    local $/;
    <$fh>
};

if ($beg eq "y") {
    $data =~ s/(?:^|(?<=\.))\Q$search\E/$replace/gim;
}

if ($end eq "y") {
    $data =~ s/\Q$search\E(?=\.|$)/$replace/gim;
}

open my $fh, '>', $file;
print $fh $data;
close $fh;

显然,你的代码可能会收紧更多,但上面的代码应该可以正常工作。