How can I get unique values from an array in Bash?

前端 未结 14 1145
-上瘾入骨i
-上瘾入骨i 2020-11-27 12:50

I\'ve got almost the same question as here.

I have an array which contains aa ab aa ac aa ad, etc. Now I want to select all unique elements from this ar

14条回答
  •  情歌与酒
    2020-11-27 13:26

    To create a new array consisting of unique values, ensure your array is not empty then do one of the following:

    Remove duplicate entries (with sorting)

    readarray -t NewArray < <(printf '%s\n' "${OriginalArray[@]}" | sort -u)
    

    Remove duplicate entries (without sorting)

    readarray -t NewArray < <(printf '%s\n' "${OriginalArray[@]}" | awk '!x[$0]++')
    

    Warning: Do not try to do something like NewArray=( $(printf '%s\n' "${OriginalArray[@]}" | sort -u) ). It will break on spaces.

提交回复
热议问题