加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

PERL可计算不可打印的字符数

发布时间:2020-12-16 06:17:34 所属栏目:大数据 来源:网络整理
导读:我有100,000个文件要分析.具体来说,我想从任意大小的文件样本中计算可打印字符的百分比.其中一些文件来自大型机,Windows,Unix等,因此很可能包含二进制和控制字符. 我开始使用Linux“文件”命令,但它没有为我的目的提供足够的细节.以下代码传达了我想要做的事
我有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):
1.)所需输出:如果目录中有932个文件,则输出将是932行文件名列表,从文件读取的总字节数和可打印字符%.
2.)许多文件都是二进制文件.脚本需要处理嵌入式二进制eol或eof序列.
3.)许多文件很大,所以我只想读取第一个/最后一个xx字节.我一直在尝试使用head -c 256或tail -c 128分别读取前256个字节或后128个字节.解决方案可以在管道中工作,也可以限制perl脚本中的字节.

解决方法

-n选项将整个代码包装一段时间(定义($_ =< ARGV>){…}块.这意味着我的$cnt_print和其他变量声明会针对每一行输入重复,基本上重置所有你的变量值.

解决方法是使用全局变量(如果你想继续使用use strict,用它们声明它们),而不是将它们初始化为0,因为它们将针对每一行输入重新初始化.你可以这么说

our $cnt_print //= 0;

如果您不希望$cnt_print及其朋友未定义第一行输入.

请参阅this recent question,其中包含类似问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读