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

perl删除文件中的重复行

发布时间:2020-12-16 00:10:20 所属栏目:大数据 来源:网络整理
导读:perl删除文件中的重复行???????????? 2011-09-28 19:59:57 ?????????? 分类: Python/Ruby 如果有一个文件data有10G大,但是有好多行都是重复的,需要将该文件中重复的行合并为一行,那么我们需要用什么办法来实现 cat data |sort|uniq new_data #该方法可以
perl删除文件中的重复行???????????? 2011-09-28 19:59:57??????????

分类: Python/Ruby

如果有一个文件data有10G大,但是有好多行都是重复的,需要将该文件中重复的行合并为一行,那么我们需要用什么办法来实现
cat data |sort|uniq > new_data #该方法可以实现,但是你需要花上好几个小时。结果才能出来。
下面是一个使用perl脚本来完成此功能的小工具。原理很简单,创建一个hash,每行的内容为键,值由每行出现的次数来填充,脚本如下;
  1. #!/usr/bin/perl
  2. # Author :CaoJiangfeng
  3. # Date:2011-09-28
  4. # Version :1.0
  5. use warnings;
  6. use strict;

  7. my %hash;
  8. my $script = $0; # Get the script name

  9. sub usage
  10. {
  11. ????????printf("Usage:n");
  12. ????????printf("perl $script <source_file> <dest_file>n");

  13. }

  14. # If the number of parameters less than 2 ,exit the script
  15. if ( $#ARGV+1 < 2) {

  16. ????????&usage;
  17. ????????exit 0;
  18. }


  19. my $source_file = $ARGV[0]; #File need to remove duplicate rows
  20. my $dest_file = $ARGV[1]; # File after remove duplicates rows

  21. open (FILE,"<$source_file")? or die "Cannot open file $!n";
  22. open (SORTED,">$dest_file") or die "Cannot open file $!n";

  23. while(defined (my $line = <FILE>))
  24. {
  25. ????????chomp($line);
  26. ?? ? ? ?$hash{$line} += 1;
  27. ?? ? ? ?#?????? print "$line,$hash{$line}n";
  28. }

  29. foreach my $k (keys %hash) {
  30. ????????print SORTED "$k,$hash{$k}n";#改行打印出列和该列出现的次数到目标文件
  31. }
  32. close (FILE);
  33. close (SORTED);

(编辑:李大同)

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

    推荐文章
      热点阅读