Shann
Shann

Reputation: 690

Perl reading file, printing unique value from a column

I am new to perl, and i'd like to achieve the following with perl.

I have a file which contain the following data:

/dev/hda1 /boot ext3 rw 0 0
/dev/hda1 /boot ext3 rw 0 0

I'd like to extract the second field from the file and print unique values only. My desired output for this example is, the program should print :

ext3

also if i have several different filesystem, it should print in on the same line.

I have tried many piece of code but am left stuck.

Thank you

Upvotes: 1

Views: 520

Answers (3)

slayedbylucifer
slayedbylucifer

Reputation: 23532

If you prefer awk:

$ cat file
/dev/hda1 /boot ext3 rw 0 0
/dev/hda1 /boot ext3 rw 0 0

$ awk '!seen[$3]++{print $3}' file
ext3

OR , using cut:

$ cut -d" " -f3 file  | sort | uniq      # or use just sort -u if your version supports it
ext3

Here is perl solution:

$ perl -lane 'print $F[2] unless $seen{$F[2]}++' file
ext3

Here is the perl command line options explanation (from perl -h):

l: enable line ending processing, specifies line terminator
a: autosplit mode with -n or -p (splits $_ into @F)
n: assume "while (<>) { ... }" loop around program
e: one line of program (several -e's allowed, omit programfile)

For a better explanation around these option, please refer: https://blogs.oracle.com/ksplice/entry/the_top_10_tricks_of

Upvotes: 6

mpapec
mpapec

Reputation: 50677

perl -anE '$s{$F[2]}++ }{say for keys %s' file

or

perl -anE '$s{$_}++ or say for $F[2]' file

Upvotes: 1

Oleg Gryb
Oleg Gryb

Reputation: 5259

#!/usr/bin/perl

my %hash ;
while (<>) {
if (/\s*[^\s]+\s+[^\s]+\s+([^\s]+)\s+.*/) {
    $hash{$1}=1;
}
}
print join("\n",keys(%hash))."\n";

Usage:

 ./<prog-name>.pl file1 fil2 ....

Upvotes: 1

Related Questions