I have a variable that contains the following space separated entries.
variable=\"apple lemon papaya avocado lemon grapes papaya apple avocado mango banana\"
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