perl删除文件中的重复行

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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值