Perl reading file, printing unique value from a column

后端 未结 3 1763
遥遥无期
遥遥无期 2021-01-24 13:09

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          


        
相关标签:
3条回答
  • 2021-01-24 13:24
    perl -anE '$s{$F[2]}++ }{say for keys %s' file
    

    or

    perl -anE '$s{$_}++ or say for $F[2]' file
    
    0 讨论(0)
  • 2021-01-24 13:27

    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

    0 讨论(0)
  • 2021-01-24 13:40
    #!/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 ....
    
    0 讨论(0)
提交回复
热议问题