我有数十万个文件需要分析,我想计算这些文件中任意大小样本的可打印字符的百分比。这些文件来自于大型机、Windows、Unix等多种平台,因此很可能包含二进制和控制字符。
我最初使用Linux的“file”命令进行分析,但它提供的细节不够满足我的需求。下面的代码可以实现我的目标,但并不总是有效。
#!/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
与其对于find返回的每一行执行脚本,它仅仅执行一次以处理所有结果。
谢谢。
到目前为止的研究:
管道、XARGS和分隔符
http://help.lockergnome.com/linux/help-understand-pipe-xargs--ftopict549399.html
http://en.wikipedia.org/wiki/Xargs#The_separator_problem
澄清:
1.) 期望的输出:如果一个目录中有932个文件,则输出将是932个文件名、读取的总字节数以及可打印字符的%的列表(共932行)。
2.) 许多文件都是二进制的。脚本需要处理嵌入的二进制 eol
或 eof
序列。
3.) 许多文件很大,因此我只想读取前/后xx字节。我一直在尝试使用 head -c 256
或 tail -c 128
分别读取前256字节或最后128字节。解决方案可以在管道线中工作,也可以在perl脚本中限制字节数。
while ($_ =~ m/[^[:print:]]/g) {$cnt_n_print++};
更好的写法是$cnt_n_print += ( () = m/[^[:print:]]/g );
(或者更好的方法是使用 tr///,但是它不支持 POSIX 类)。 - ysth-n
! - Borodin