指定したディレクトリ配下のファイル内のタブをスペースに変換するperlスクリプト replaceTabToSpace.pl を作成した。使い方は簡単で「perl replaceTabToSpace.pl "ディレクトリのパス"」で実行できる。
例えば、ソースコード内にタブとスペースが混在していて見にくい状態になっていて、それらを全てスペースに統一したい時に使うと便利。対象となるファイル数が少なかったら、テキストエディタの置換機能で1ファイルずつタブ⇒スペースへの置換を行えば良いが、対象となるファイル数が多数あった時は1ファイルずつ対処すると面倒なので、このスクリプトを作成した。
use strict;
use warnings;
my $dir = $ARGV[0];
if(! -d $dir) {
die "Invalid argument. Specify a dir...";
}
my $NUM_OF_SPACE = 4;
my $spaces = ' ' x $NUM_OF_SPACE;
my @fileList;
getFileList($dir, \@fileList);
foreach my $file (@fileList) {
if(-f $file) {
my $tmpOutFile = "$file.replaced";
open(my $in, $file) or die "Failed to open $file: $!";
open(my $out, ">$tmpOutFile") or die "Failed to open $tmpOutFile: $!";
foreach my $line (<$in>) {
$line =~ s/\t/$spaces/g;
print($out $line);
}
close($in);
close($out);
rename($tmpOutFile, $file) or die "Failed to rename $tmpOutFile to $file: $!";
}
}
sub getFileList {
my $dir = shift;
my $ref_fileList = shift;
opendir(my $dh, $dir) or die "Failed to open $dir: $!";
my @fileList = readdir($dh);
closedir($dh);
foreach my $file (sort @fileList) {
if($file =~ /^\.{1,2}$/) {
next;
}
if( -d "$dir/$file") {
getFileList("$dir/$file", $ref_fileList);
}
else {
push(@$ref_fileList, "$dir/$file");
}
}
}
なお、タブをスペース幾つに変換するかは、上記の
my $NUM_OF_SPACE = 4;
で指定する。