假如有這樣的一段序列:
1 2
1 2
2 1
1 3
1 4
1 5
4 1
我們需要得到如下的結(jié)果:
1 3
1 5
2 1
4 1
那么,請(qǐng)借助以下的perl腳本來實(shí)現(xiàn)。
代碼一:
代碼如下:
#!/bin/perl
use strict;
use warnings;
my $filename;
my %hash;
my @information;
my $key1;
my $key2;
print "please put in the file like this f:////perl////data.txt/n";
chomp($filename=<STDIN>);
open(IN,"$filename")||die("can not open");
while(<IN>)
{
chomp;
@information=split//s+/,$_;
if(exists $hash{$information[0]}{$information[1]})
{
next;
}
else
{
$hash{$information[0]}{$information[1]}='A';
}
}
close IN;
open(IN,"$filename")||die("can not open");
while(<IN>)
{
@information=split//s+/,$_;
if(exists $hash{$information[1]}{$information[0]})
{
delete $hash{$information[0]}{$information[1]}
}
else
{
next;
}
}
close IN;
open(OUT,">f://A_B_result.txt")||die("can not open");
foreach $key1 (sort{$a<=>$b} keys %hash)
{
foreach $key2 (sort{$a<=>$b} keys %{$hash{$key1}})
{
print OUT "$key1 $key2/n";
}
}
close OUT;
代碼二:
如果有一個(gè)文件data有10G大,但是有好多行都是重復(fù)的,需要將該文件中重復(fù)的行合并為一行,那么我們需要用什么辦法來實(shí)現(xiàn)
cat data |sort|uniq > new_data #該方法可以實(shí)現(xiàn),但是你需要花上好幾個(gè)小時(shí)。結(jié)果才能出來。
下面是一個(gè)使用perl腳本來完成此功能的小工具。原理很簡(jiǎn)單,創(chuàng)建一個(gè)hash,每行的內(nèi)容為鍵,值由每行出現(xiàn)的次數(shù)來填充,腳本如下;
代碼如下:
#!/usr/bin/perl
# Author :CaoJiangfeng
新聞熱點(diǎn)
疑難解答
圖片精選