简体   繁体   English

唯一值的计算直接在Shell中有效,而在反引号中则无效

[英]Counting unique values works directly in shell but not in backticks

I am trying to figure out why this works from the command line however does not when it is in a variable, I am trying to count the number of unique occurrences of a number, 我试图弄清为什么它在命令行中起作用,但是当它在变量中时却不起作用,我试图计算一个数字唯一出现的次数,

$ echo 1,1,2,3,4,5 | tr , \\n | sort -u | wc -l
5
$ test=`echo 1,1,2,3,4,5 | tr , \\n | sort -u | wc -l`
$ echo $test
1

I am assuming that it is seen as one line when in a variable but unsure why and how to address it? 我假设它在变量中被视为一行,但不确定为什么以及如何解决?

Thanks! 谢谢!

you may see what is happening by putting set -x : 您可以通过set -x来查看发生了什么:

$ test=`set -x; echo 1,1,2,3,4,5 | tr , \\n | sort -u | wc -l`
++ echo 1,1,2,3,4,5
++ tr , n
++ wc -l

here you see that the \\n became n 在这里,您看到\\n变为n

the escape of \\n fails; \\n的转义失败; try 尝试

test=`echo 1,1,2,3,4,5 | tr , '\n' | sort -u | wc -l`

the quotes will prevent the `\\' to fade away 引号将阻止“ \\”消失

or even 甚至

 test=$(echo 1,1,2,3,4,5 | tr , '\n' | sort -u | wc -l)

as we usually prefere $() to backquotes that can cause some other kind of trouble 因为我们通常更喜欢$()而不可能引起其他麻烦的反引号

Using awk you can avoid all the piped commands: 使用awk可以避免使用所有管道命令:

count=$(echo 1,1,2,3,4,5 | awk -v RS=, '!seen[$1]++{c++} END{print c}')
echo $count
5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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