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

前端 未结 14 1173
-上瘾入骨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:12

    Another option for dealing with embedded whitespace, is to null-delimit with printf, make distinct with sort, then use a loop to pack it back into an array:

    input=(a b c "$(printf "d\ne")" b c "$(printf "d\ne")")
    output=()
    
    while read -rd $'' element
    do 
      output+=("$element")
    done < <(printf "%s\0" "${input[@]}" | sort -uz)
    

    At the end of this, input and output contain the desired values (provided order isn't important):

    $ printf "%q\n" "${input[@]}"
    a
    b
    c
    $'d\ne'
    b
    c
    $'d\ne'
    
    $ printf "%q\n" "${output[@]}"
    a
    b
    c
    $'d\ne'
    

提交回复
热议问题