Removing duplicates on a variable without sorting

后端 未结 8 1091
陌清茗
陌清茗 2020-12-28 23:30

I have a variable that contains the following space separated entries.

variable=\"apple lemon papaya avocado lemon grapes papaya apple avocado mango banana\"         


        
8条回答
  •  梦谈多话
    2020-12-29 00:03

    Perl solution:

    perl -le 'for (@ARGV){ $h{$_}++ }; for (keys %h){ print $_ }' $variable

    @ARGV is the list of input parameters from $variable
    Loop through the list, populating the h hash with the loop variable $_
    Loop through the keys of the h hash, and print each one

    grapes
    avocado
    apple
    lemon
    banana
    mango
    papaya
    

    This variation prints the output sorted first by frequency $h{$a} <=> $h{$b} and then alphabetically $a cmp $b

    perl -le 'for (@ARGV){ $h{$_}++ }; for (sort { $h{$a} <=> $h{$b} || $a cmp $b } keys %h){ print "$h{$_}\t$_" }' $variable

    1       banana
    1       grapes
    1       mango
    2       apple
    2       avocado
    2       lemon
    2       papaya
    

    This variation produces the same output as the last one.
    However, instead of an input shell variable, uses an input file 'fruits', with one fruit per line:

    perl -lne '$h{$_}++; END{ for (sort { $h{$a} <=> $h{$b} || $a cmp $b } keys %h){ print "$h{$_}\t$_" } }' fruits

提交回复
热议问题