Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash remove duplicate string from list [duplicate]

Tags:

string

grep

bash

I want to delete duplicate strings from a String. Example:

A="Dog Cat Horse Dog Dog Cat"

The string A should look like this:

A="Dog Cat Horse"

How can I write a Shell script for that?

like image 403
Anne K. Avatar asked Jul 14 '26 08:07

Anne K.


2 Answers

You could use this,

echo "a a b b c c" | tr ' ' '\n' | sort | uniq | tr '\n' ' ' | sed -e 's/[[:space:]]*$//'
like image 130
Adishesh Kishore Avatar answered Jul 16 '26 11:07

Adishesh Kishore


If order is not important, you can use an associative array:

declare -A uniq
for k in $A ; do uniq[$k]=1 ; done
echo ${!uniq[@]}
like image 34
choroba Avatar answered Jul 16 '26 12:07

choroba