ablog

不器用で落着きのない技術者のメモ

再帰的にファイル内の文字列を置換するPerlスクリプト

WindowsCygwin などが入ってなくて、find とか xargs とかない場合に使う Perl スクリプトを書いてみた。

#!/usr/bin/env perl

use strict;
use warnings;
use File::Find;
use File::Basename;

&print_usage if ($#ARGV < 0);
find(\&process, $ARGV[0]);

sub process {
	my $org_filename = $_;
	my $new_filename = "$org_filename.tmp";

	return unless -f $org_filename;

	open (my $IN, "<", $org_filename) 
		or warn "cannot open $org_filename because $! \n";
	open (my $OUT, ">", $new_filename) 
		or warn "cannot create $new_filename because $! \n";

	while (<$IN>) {
		s/"//g;
		print $OUT $_;
	}
	close ($IN);
	close ($OUT);

	rename($org_filename, "$org_filename.org") 
		or warn "cannot rename $org_filename because $! \n";
	rename($new_filename, $org_filename) 
		or warn "cannot rename $new_filename because $! \n";
}

sub print_usage {
	my $script_name = basename($0);
	print "$script_name: missing argument\n";
	print "Usage  : perl $script_name directory\n";
	print "Example: perl $script_name ./log\n";
	exit(1);
}

__END__