0

let's say I have an array that goes like this (a a b b b c c d) I want the array to have only one each character/string (a b c d) is there any way converting the array into lines so I can use sort & uniq without temp file?

thanks !

Itai Bar
  • 747
  • 5
  • 14
  • Not able to get what do you mean by `array into lines`? – prashant thakre Aug 12 '14 at 18:51
  • 1
    possible duplicate of [How can I get unique values from an array in linux bash?](http://stackoverflow.com/questions/13648410/how-can-i-get-unique-values-from-an-array-in-linux-bash) – dsemi Aug 12 '14 at 18:53

3 Answers3

5

You can use the printf command.

printf "%s\n" "${array[@]}" | sort | uniq

This will print each element of array followed by a newline to standard output.

To repopulate the array, you might use

readarray -t array < <(printf "%s\n" "${array[@]}" | sort | uniq)

However, you might instead simply use an associative array to filter out the duplicates.

declare -A aa
for x in "${array[@]}"; do
    aa[$x]=1
done
array=()
for x in "${!aa[@]}"; do
    array+=("$x")
done
chepner
  • 497,756
  • 71
  • 530
  • 681
1

As a curiosity, the:

arr=(a a b b b c c d)
echo "${arr[@]}" | xargs -n1 | sort -u

prints

a
b
c
d

and the

echo "${arr[@]}" | xargs -n1 | sort -u | xargs

prints

a b c d
clt60
  • 62,119
  • 17
  • 107
  • 194
-2
 for x in a a b b b c c d; do echo -e $x; done | sort | uniq
leogtzr
  • 480
  • 4
  • 7