I have a string which is something like 50003 50003 50003 50001 this I get after processing into another file which is stored into a variable. now i want from that variable unique words. Like 50003 50001 how to do this?

  • Are you using bash, zsh, python, c (etc) ?\ – cremefraiche Dec 13 '15 at 5:18

You could pipe it through tr, sort, uniq, for example on command prompt you can test this:

 $ var1='50003 50003 50003 50001 50003'


 $ echo $var1 | tr ' ' '\n' | sort | uniq

As you can see it outputs unique, and sorts it in case you want to do something with it later that requires sorted input.


For your additional question in comments, if you wish to save the results into a variable, you can, in script:

var2="$( echo $var1 | tr ' ' '\n' | sort | uniq )"
  • $( ... ) is a bash command substitution, replacing the contents of $(...) with the commands' output

So later in your script if you wish to output $var2 to the terminal, just:

echo "$var2"
  • enclose $var2 in quotes in order to continue to display it as one line per result
  • otherwise without quotes, echo by default interprets each "word" in $var2 as a separate argument, will output it one by one separated by space, so you end up with one long sentence instead.

Also remember you can save output to a file such as ~/unique_results.txt:

echo $var1 | tr ' ' '\n' | sort | uniq  > ~/unique_results.txt
  • > is file redirection, redirects standard out to specified file
  • Above solution works but hot to store the value of echo $var1 | tr ' ' '\n' | sort | uniq in a variable : var2=echo $var1 | tr ' ' '\n' | sort | uniq does not work, echo $var2 is nothing – Girija Joshi Dec 14 '15 at 3:59

If this is in bash, the following will print only the uniq words in a stored variable named herpderp:

for w in $herpderp; do echo $w ; done | uniq

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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