Perl getting unique values from file column [dupli

2019-08-14 09:40发布

This question already has an answer here:

i have a file that has the following data:

col1 col2 ext3 rw
col1 col2 ext3 rw 
col1 col2 ext3 rw 
col1 col2 nfs rw 
col1 col2 ext4 rw 
col1 col2 iso9660 ro

what am trying to do is to read the file and print unique values from column 3. The column 3 contains the ext3,ext4,nfs ...

currently my output is:

ext3 
ext3 
ext3 
nfs 
ext4 
iso9660

and my output should be :

ext3
nfs
ext4
iso9660

Below is what i have tried till now:

#!/usr/bin/perl    
use strict;
use warnings; 
my $filename = $ARGV[0];
open(FILE, $filename) or die "Could not open file '$filename' $!";
while (<FILE>)
{
    chomp;
    my $line = $_;
    my @elements = split (" ", $line);
    my $row_name = $elements[2];
    print $row_name . "\n";

}
close FILE;

How do i make it print the unique values in the same program? Thank you.

2条回答
萌系小妹纸
2楼-- · 2019-08-14 10:08

Using a perl oneliner

perl -lane 'print $F[2] if ! $seen{$F[2]}++' file.txt

Or within your script, by adding a %seen hash as demonstrated in perlfaq4 How can I remove duplicate elements from a list or array?

use strict;
use warnings; 
my $filename = $ARGV[0];
open(FILE, $filename) or die "Could not open file '$filename' $!";
my %seen;
while (<FILE>)
{
    chomp;
    my $line = $_;
    my @elements = split (" ", $line);
    my $row_name = $elements[2];
    print $row_name . "\n" if ! $seen{$row_name}++;
}
close FILE;
查看更多
smile是对你的礼貌
3楼-- · 2019-08-14 10:15

You can use a hash to keep track of which values have been seen before.

Also, files named on the command line don't need to be explicitly opened. You can read from them using <>, like this

use strict;
use warnings; 

my %seen;
while (<>) {
  my $col3 = (split)[2];
  print "$col3\n" unless $seen{$col3}++;
}

output

ext3
nfs
ext4
iso9660
查看更多
登录 后发表回答