6

入力ファイル、出力ファイルを取り込み、入力ファイルの文字列を他の文字列に置き換えて出力ファイルを書き出す次のスクリプトがあります。

ファイルのディレクトリをトラバースするようにスクリプトを変更したい。つまり、入力ファイルと出力ファイルを要求する代わりに、スクリプトは C:\temp\allFilesTobeReplaced\ などのディレクトリ パスを引数として取り、文字列 x を検索して置換する必要があります。そのディレクトリ パスの下のすべてのファイルに対して y を指定し、同じファイルを書き出します。

どうすればいいですか?

ありがとう。

$file=$ARGV[0];

open(INFO,$file);
@lines=<INFO>;
print @lines;

open(INFO,">c:/filelist.txt");

foreach $file (@lines){
   #print "$file\n";
   print INFO "$file";
}

#print "Input file name: ";
#chomp($infilename = <STDIN>);

if ($ARGV[0]){
   $file= $ARGV[0]
}

print "Output file name: ";
chomp($outfilename = <STDIN>);
print "Search string: ";
chomp($search = <STDIN>);
print "Replacement string: ";
chomp($replace = <STDIN>);

open(INFO,$file);
@lines=<INFO>;
open(OUT,">$outfilename") || die "cannot create $outfilename: $!";

foreach $file (@lines){    
    # read a line from file IN into $_
    s/$search/$replace/g; # change the lines
    print OUT $_; # print that line to file OUT
}
close(IN);
close(OUT);
4

5 に答える 5

12

perl シングルライナーの使用

perl -pi -e 's/original string/new string/' filename

と組み合わせてFile::Find、次の単一のスクリプトを作成できます (これは、私がそのような多くの操作に使用するテンプレートです)。

use File::Find;

# search for files down a directory hierarchy ('.' taken for this example)
find(\&wanted, ".");

sub wanted
{
    if (-f $_)
    {
        # for the files we are interested in call edit_file().
        edit_file($_);
    }
}

sub edit_file
{
    my ($filename) = @_;

    # you can re-create the one-liner above by localizing @ARGV as the list of
    # files the <> will process, and localizing $^I as the name of the backup file.
    local (@ARGV) = ($filename);
    local($^I) = '.bak';

    while (<>)
    {
        s/original string/new string/g;
    }
    continue
    {
        print;
    }
}
于 2009-05-27T23:09:25.753 に答える
2

-i パラメータを使用してこれを行うことができます。

すべてのファイルを通常どおりに処理しますが、-i.bak を含めます。

#!/usr/bin/perl -i.bak

while ( <> ) {
   s/before/after/;
   print;
}

これにより、各ファイルが処理され、オリジナルの名前が original.bak に変更されます。もちろん、@Jamie Cook で言及されているように、ワンライナーとして実行できます。

于 2009-05-28T16:30:05.593 に答える
1

これを試して

#!/usr/bin/perl -w

@files = <*>;
foreach $file (@files) {
  print $file . '\n';
}

Perl の glob も見てみましょう:

于 2009-05-27T21:41:01.720 に答える