new_variable=$( awk 'BEGIN{RS=ORS=" "}!a[$0]++' <<<$variable );
Here's how it works:
The RS (Input Record Separator) is set to empty space, so that it treats each fruit in the $ variable as a record instead of a field. Unique magic without sorting happens with! A [$ 0] ++. Since awk supports associative arrays, it uses the current entry ($ 0) as the key to a [] array. If this key has not yet been seen, the value [$ 0] evaluates to "0" (the default awk value for undefined indexes), which is then canceled to return TRUE. Then I use the fact that awk will "print $ 0" by default if the expression returns TRUE and no '{commands}'. Finally, [$ 0] is incremented, so that this key can no longer return TRUE, and therefore repeat values ββare never printed. ORS (Output Record Separator) is also set to space to simulate the input format.
A less complex version of this command that produces the same output will be as follows:
awk 'BEGIN{RS=ORS=" "}{ if (a[$0] == 0){ a[$0] += 1; print $0}}'
Gotta love awk =)
EDIT
If you needed to do this in pure Bash 2.1+, I would suggest the following:
#!/bin/bash variable="apple lemon papaya avocado lemon grapes papaya apple avocado mango banana" temp="$variable" new_variable="${temp%% *}" while [[ "$temp" != ${new_variable##* } ]]; do temp=${temp//${temp%% *} /} new_variable="$new_variable ${temp%% *}" done echo $new_variable;
Siegex
source share