如何将命令的输出除以二,并将结果存储到 bash 变量中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2314376/
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
How do I divide the output of a command by two, and store the result into a bash variable?
提问by KP65
Say if i wanted to do this command:
说如果我想做这个命令:
(cat file | wc -l)/2
and store it in a variable such as middle, how would i do it?
并将其存储在诸如中间的变量中,我该怎么做?
I know its simply not the case of
我知道这根本不是
$middle=$(cat file | wc -l)/2
so how would i do it?
那我该怎么做呢?
回答by blahdiblah
middle=$((`wc -l < file` / 2))
回答by Steve Emmerson
middle=$((`wc -l file | awk '{print }'`/2))
回答by Paused until further notice.
This relies on Bash being able to reference the first element of an array using scalar syntax and that is does word splitting on white space by default.
这依赖于 Bash 能够使用标量语法引用数组的第一个元素,即默认情况下在空格上进行分词。
middle=($(wc -l file)) # create an array which looks like: middle='([0]="57" [1]="file")'
middle=$((middle / 2)) # do the math on ${middle[0]}
The second line can also be:
第二行也可以是:
((middle /= 2))
回答by jonescb
When assigning variables, you don't use the $
分配变量时,不要使用 $
Here is what I came up with:
这是我想出的:
mid=$(cat file | wc -l)
middle=$((mid/2))
echo $middle
The double parenthesis are important on the second line. I'm not sure why, but I guess it tells Bash that it's not a file?
双括号在第二行很重要。我不知道为什么,但我猜它告诉 Bash 它不是一个文件?
回答by ghostdog74
using awk.
使用awk。
middle=$(awk 'END{print NR/2}' file)
you can also make your own "wc" using just the shell.
您还可以仅使用外壳制作自己的“wc”。
linec(){
i=0
while read -r line
do
((i++))
done < ""
echo $i
}
middle=$(linec "file")
echo "$middle"

