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?
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 50001 50003
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:
$var2in quotes in order to continue to display it as one line per result
- otherwise without quotes,
echoby default interprets each "word" in
$var2as 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
echo $var1 | tr ' ' '\n' | sort | uniq > ~/unique_results.txt
>is file redirection, redirects standard out to specified file
If this is in bash, the following will print only the uniq words in a stored variable named
for w in $herpderp; do echo $w ; done | uniq