我有 100,000 个文件要分析。具体来说,我想从任意大小的文件样本中计算可打印字符的百分比。其中一些文件来自大型机、Windows、Unix 等,因此很可能包含二进制和控制字符。
我从使用 Linux 的“文件”命令开始,但它没有为我的目的提供足够的细节。以下代码传达了我想要做的事情,但并不总是有效。
#!/usr/bin/perl -n
use strict;
use warnings;
my $cnt_n_print = 0;
my $cnt_print = 0;
my $cnt_total = 0;
my $prc_print = 0;
#Count the number of non-printable characters
while ($_ =~ m/[^[:print:]]/g) {$cnt_n_print++};
#Count the number of printable characters
while ($_ =~ m/[[:print:]]/g) {$cnt_print++};
$cnt_total = $cnt_n_print + $cnt_print;
$prc_print = $cnt_print/$cnt_total;
#Print the # total number of bytes read followed by the % printable
print "$cnt_total|$prc_print\n"
这是一个有效的测试调用:
echo "test_string of characters" | /home/user/scripts/prl/s16_count_chars.pl
这就是我打算调用它的方式,并且适用于一个文件:
find /fct/inbound/trans/ -name "TRNST.20121115231358.xf2" -type f -print0 | xargs -0 head -c 2000 | /home/user/scripts/prl/s16_count_chars.pl
这不能正常工作:
find /fct/inbound/trans/ -type f -print0 | xargs -0 head -c 2000 | /home/user/scripts/prl/s16_count_chars.pl
这也不是:
find /fct/inbound/trans/ -type f -print0 | xargs -0 head -c 2000 | perl -0 /home/user/scripts/prl/s16_count_chars.pl
它不是为查找返回的每一行执行一次脚本,而是为所有结果执行一次。
提前致谢。
迄今为止的研究:
管道和 XARGS 以及分隔符
http://help.lockergnome.com/linux/help-understand-pipe-xargs--ftopict549399.html
http://en.wikipedia.org/wiki/Xargs#The_separator_problem
澄清:
1.) 所需输出:如果目录中有 932 个文件,则输出将是 932 行文件名列表、从文件读取的总字节数和可打印字符的百分比。
2.) 许多文件是二进制文件。脚本需要处理嵌入的二进制eol
或eof
序列。
3.)许多文件很大,所以我只想读取第一个/最后一个 xx 字节。我一直试图分别使用head -c 256
或tail -c 128
读取前 256 个字节或后 128 个字节。解决方案可以在管道中工作,也可以在 perl 脚本中限制字节。