从 Linux bash shell 脚本中的两个变量创建唯一列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12533012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a unique list from two variables in a Linux bash shell script
提问by Shawn Vader
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"
回答by imp25
The following pipes a combination of the two lists through the sortprogram with the unique parameter -u:
以下通过sort具有唯一参数的程序管道将两个列表的组合-u:
UNIQUE=$(echo "$VAR1 $VAR2" | tr ' ' '\n' | sort -u)
This gives the output:
这给出了输出:
> echo $UNIQUE
SERVER1 SERVER2 SERVER3 SERVER5
Edit:
编辑:
As William Purcellpoints 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' ' ':
正如威廉珀塞尔在下面的评论中指出的那样,这将用换行符分隔字符串。如果您想再次用空格分隔,您可以通过管道将 sort 的输出传回tr '\n' ' ':
> UNIQUE=$(echo "$VAR1 $VAR2" | tr ' ' '\n' | sort -u | tr '\n' ' ')
> echo "$UNIQUE"
SERVER1 SERVER2 SERVER3 SERVER5
回答by ferbuntu
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.
一个接一个地放置一个变量是我所知道的最简单的连接方式。也许对于你的计划还不够。但它有效并且对于简单的任务很有用。它对任何变量都有用。
回答by William Pursell
If you need to maintain the order, you cannot use sort, but you can do:
如果您需要维护订单,则不能使用sort,但您可以这样做:
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 FOOwill not be added if FOOSERVERis already in the list, but this is a good technique.
这会附加到 VAR3,因此您可能希望先清除 VAR3。此外,您可能需要在将单词边界放在 grep 上时更加小心,因为FOO如果FOOSERVER已经在列表中,则不会添加,但这是一个很好的技术。

