数组去重

数组和集合 / 数组

numbers=(1 3 2 1 3)

#sort -u 排序并去掉重复项(-n 按数字比较)
mapfile -t unique < <(printf '%s\n' "${numbers[@]}" | sort -nu)
#unique is (1 2 3)

#uniq 只去掉相邻的重复项,
#所以没有 sort 时,它在这里不起任何作用
mapfile -t notSorted < <(printf '%s\n' "${numbers[@]}" | uniq)
#notSorted is (1 3 2 1 3)

#按首次出现的顺序:awk 对每一行,
#只在第一次遇到时才打印
mapfile -t firstOrder < <(printf '%s\n' "${numbers[@]}" | awk '!seen[$0]++')
#firstOrder is (1 3 2)

echo "unique is (${unique[*]})"
echo "notSorted is (${notSorted[*]})"
echo "firstOrder is (${firstOrder[*]})"