Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

If I have a list in bash

L="11 22 11 33 22 44"

Is there a clean way to get to "11 22 33 44" ?

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

One way:

$ L="11 22 11 33 22 44"
$ L=$(echo $L | tr ' ' '\n' | sort -nu)    
$ echo $L
11 22 33 44

Using tr, the numbers are split to individual lines, and sort is used to sort the numbers(-n) and remove the duplicate ones(-u).

share|improve this answer
    
You can leave off the | xargs. Because of the way the shell handles multi-line output from a $(…) command, L=$(echo $L | tr ' ' '\n' | sort –u) is enough. –  Scott Dec 1 '12 at 1:42
    
@Scott : thanks scott for pointing it out, updated the solution.... –  Guru Dec 1 '12 at 1:45
    
Clean and easy. 'tr' was the the part I was missing. –  Travis Bear Dec 1 '12 at 1:49
add comment

A common pattern in some other programming languages is to store each value as a 'key' in a hash or dictionary or associative array, and rely on the implementation to keep hash keys unique.

declare -A items=()
for item in $L; do
    items[$item]=1
done
L=${!items[*]}

(Unfortunately, the bash implementation is about 2× slower than sort -u.)

share|improve this answer
    
+1..its always a pleasure looking at pure shell solutions.. –  Guru Dec 1 '12 at 2:04
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.