简体   繁体   中英

Create a unique list from two variables in a Linux bash shell script

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"

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM