0

I have a variable $var with this content:

var=word1,word2,word3,word1,word3

and I need to delete duplicate words and the results is required stored in the same variable $var.

unor
  • 92,415
  • 26
  • 211
  • 360
Matias Araya
  • 49
  • 1
  • 8

2 Answers2

1

Try

    var="word1,word2,word3,word1,word3"
    list=$(echo $var | tr "," "\n")
    var=($(printf "%s\n" "${list[@]}" | sort | uniq -c | sort -rnk1 | awk '{ print $2 }'))
 echo  "${var[@]}"
tesnik03
  • 1,324
  • 2
  • 13
  • 23
0

If open to perl then:

$ var="word1,word2,word3,word1,word3"
$ var=$(perl -F, -lane'{$h{$_}++ or push @a, $_ for @F; print join ",", @a}' <<< "$var")
$ echo "$var"
word1,word2,word3
jaypal singh
  • 74,723
  • 23
  • 102
  • 147