从Perl的文件栏获取唯一值 [英] Perl getting unique values from file column
问题描述
我有一个具有以下数据的文件:
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
什么我试图做的是阅读文件,并从第3列列3包含ext3的打印独特的价值观,EXT4,NFS ...
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 ...
目前我的输出是:
ext3
ext3
ext3
nfs
ext4
iso9660
和我的输出应该是:
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.
推荐答案
使用一个Perl oneliner
Using a perl oneliner
perl -lane 'print $F[2] if ! $seen{$F[2]}++' file.txt
或者你的脚本中,加入了%看过
哈希值表现在<一个href=\"http://perldoc.perl.org/perlfaq4.html#How-can-I-remove-duplicate-elements-from-a-list-or-array%3f\"相对=nofollow> perlfaq4如何删除从列表或数组重复的元素?
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;
这篇关于从Perl的文件栏获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!