PERL可计算不可打印的字符数
我有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_printn" 这是一个有效的测试调用: 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 对于查找返回的EACH行,它不执行一次脚本,而是对所有结果执行ONCE. 提前致谢. 迄今为止的研究: 管道和XARGS和分隔符 http://help.lockergnome.com/linux/help-understand-pipe-xargs–ftopict549399.html http://en.wikipedia.org/wiki/Xargs#The_separator_problem 澄清(S): 解决方法
-n选项将整个代码包装一段时间(定义($_ =< ARGV>){…}块.这意味着我的$cnt_print和其他变量声明会针对每一行输入重复,基本上重置所有你的变量值.
解决方法是使用全局变量(如果你想继续使用use strict,用它们声明它们),而不是将它们初始化为0,因为它们将针对每一行输入重新初始化.你可以这么说 our $cnt_print //= 0; 如果您不希望$cnt_print及其朋友未定义第一行输入. 请参阅this recent question,其中包含类似问题. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |