项目中有的代码空行过多,这里用脚本批量处理一下,规范代码,把换行符连续3个以上的统一规范为两个换行符。以C++项目为例,脚本中处理后缀为 (h|hpp|cpp|cc) 的代码文件,perl脚本如下:
#! /usr/bin/perl
use v5.14;
use File::Find;
use IO::File;
my @filesArry = ();
my $callback = sub {
# 根据需要自行修改正则
push @filesArry, $File::Find::name if m{\.(h|hpp|cpp|cc)$};
};
find($callback, "./");
sub getFileContent {
my $fileName = shift;
my $handle = IO::File->new($fileName, 'r');
$handle->read(my $buffer, -s $handle);
return $buffer;
}
for my $filePath (@filesArry) {
my $content = getFileContent($filePath);
my $old = $content;
if ($content =~ /\r\n/) {
$content =~ s/(\r\n){3,}/\r\n\r\n/g;
} elsif ($content =~ /\n/) {
$content =~ s/\n{3,}/\n\n/g;
}
if ($content ne $old) {
my $handle = IO::File->new($filePath, 'w');
$handle->write($content);
say "[PROCESS]: $filePath";
}
}
脚本默认从执行的当前目录开始搜索。