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.
Using a perl oneliner
Or within your script, by adding a
%seen
hash as demonstrated inperlfaq4 How can I remove duplicate elements from a list or array?
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 thisoutput