【发布时间】:2012-11-09 02:46:27
【问题描述】:
我有 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 脚本中限制字节。
【问题讨论】:
-
while ($_ =~ m/[^[:print:]]/g) {$cnt_n_print++};最好是$cnt_n_print += ( () = m/[^[:print:]]/g );(或者更好的是,使用 tr///,只是不支持 POSIX 类) -
"Better" = 更快、更简洁,但使用更多内存。实际上,可能更多。 (每个匹配字符的整个字符串标量!)
-
不!不是
-n在 shebang 线上!
标签: perl ascii non-ascii-characters non-printable