0

I have two variables which have values that can be in both. I would like to create a unique list from the two variables.

VAR1="SERVER1 SERVER2 SERVER3"
VAR2="SERVER1 SERVER5"

I am trying to get a result of:

"SERVER1 SERVER2 SERVER3 SERVER5"
1

4 Answers 4

6

The following pipes a combination of the two lists through the sort program with the unique parameter -u:

UNIQUE=$(echo "$VAR1 $VAR2" | tr ' ' '\n' | sort -u)

This gives the output:

> echo $UNIQUE
SERVER1 SERVER2 SERVER3 SERVER5

Edit:

As William Purcell points out in the comments below, this separates the strings by new-lines. If you wish to separate by white space again you can pipe the output from sort back through tr '\n' ' ':

> UNIQUE=$(echo "$VAR1 $VAR2" | tr ' ' '\n' | sort -u | tr '\n' ' ')
> echo "$UNIQUE"
SERVER1 SERVER2 SERVER3 SERVER5
Sign up to request clarification or add additional context in comments.

1 Comment

But note that $UNIQUE has newlines for whitespace. (Try echo "$UNIQUE")
1

And of course you have

$ var1="a b c"
$ result=$var1" d e f"
$ echo $result

With that you achieve the concatenation.

Also with variables:

$ var1="a b c"
$ var2=" d e f"
$ result=$var1$var2
$ echo $result

To put a variable after another is the simpliest way of concatenation i know. Maybe for your plans is not enough. But it works and is usefull for easy tasks. It will be usefull for any variable.

1 Comment

This ignores the bigger part of the question, which is to eliminate the duplicates.
1

If you need to maintain the order, you cannot use sort, but you can do:

for i in $VAR1 $VAR2; do echo "$VAR3" | grep -qF $i || VAR3="$VAR3${VAR3:+ }$i"; done

This appends to VAR3, so you probably want to clear VAR3 first. Also, you may need to be more careful in terms of putting word boundaries on the grep, as FOO will not be added if FOOSERVER is already in the list, but this is a good technique.

Comments

0

Use printf '%s\n' to avoid having to | tr ' ' '\n

printf '%s\n' "$TEST_VAR1" "$TEST_VAR2" | sort -u

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.