unixscriptingkshmks

Remove duplicated string stored in variable


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.


Solution

  • 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[@]}"