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 !

2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

3 Comments

You can also combine the ... | sort | uniq into ... | sort -u
Or array=("${!aa[@]}").
<shakes head> Why on earth did I write that second for loop?
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

Comments

-2
 for x in a a b b b c c d; do echo -e $x; done | sort | uniq

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.