如何在 Linux 控制台中进行划分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1088098/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 17:29:36  来源:igfitidea点击:

How do I divide in the Linux console?

linuxmathcommand-linedivide

提问by kman99

I have to variables and I want to find the value of one divided by the other. What commands should I use to do this?

我必须变量,我想找到一个除以另一个的值。我应该使用什么命令来做到这一点?

回答by Paolo Capriotti

I assume that by Linux consoleyou mean Bash.

我认为Linux 控制台是指Bash

If Xand Yare your variables, $(($X / $Y))returns what you ask for.

如果XY是您的变量,则$(($X / $Y))返回您要求的内容。

回答by dave4420

In the bash shell, surround arithmetic expressions with $(( ... ))

在 bash shell 中,将算术表达式用 $(( ... ))

$ echo $(( 7 / 3 ))
2

Although I think you are limited to integers.

虽然我认为你仅限于整数。

回答by Draemon

Example of integer division using bash to divide $a by $b:

使用 bash 将 $a 除以 $b 的整数除法示例:

echo $((a/b))

回答by Mark Rushakoff

In bash, if you don't need decimals in your division, you can do:

在 bash 中,如果你的部门不需要小数,你可以这样做:

>echo $((5+6))
11
>echo $((10/2))
5
>echo $((10/3))
3

回答by libHyman

I still prefer using dc, which is an RPN calculator, so quick session to divide 67 by 18 with 4 digits precision would look like

我仍然更喜欢使用dc,它是一个 RPN 计算器,所以用 4 位精度将 67 除以 18 的快速会话看起来像

>dc
4k
67
18/p
3.7222
q
>

Obviously, much more available: man dc

显然,还有更多可用的:man dc

回答by user1504475

Better way is to use "bc", an arbitrary precision calculator.

更好的方法是使用“bc”,一个任意精度的计算器。

variable=$(echo "OPTIONS; OPERATIONS" | bc)

ex:

前任:

my_var=$(echo "scale=5; $temp_var/100 + $temp_var2" | bc)

where "scale=5" is accuracy.

其中“scale=5”是准确度。

man bc 

comes with several usage examples.

附带几个使用示例。

回答by raytrace

echo 5/2 | bc -l

2.50000000000000000000

2.50000000000000000000

this '-l' option in 'bc' allows floating results

'bc' 中的这个 '-l' 选项允许浮动结果

回答by 2upmedia

Something else you could do using raytrace's answer. You could use the stdout of another shell call using backticks to then do some calculations. For instance I wanted to know the file size of the top 100 lines from a couple of files. The original size from wc -cis in bytes, I want to know kilobytes. Here's what I did:

您可以使用 raytrace 的答案做其他事情。您可以使用使用反引号的另一个 shell 调用的标准输出来进行一些计算。例如,我想知道几个文件中前 100 行的文件大小。from 的原始大小wc -c以字节为单位,我想知道千字节。这是我所做的:

echo `cat * | head -n 100 | wc -c` / 1024 | bc -l

回答by jperrie

You can use awkwhich is a utility/language designed for data extraction

您可以使用awk,这是一种专为数据提取而设计的实用程序/语言

e.g. for 1.2/3.4

例如对于 1.2/3.4

>echo 1.2 3.4 | awk '{ print / }'
0.352941

回答by JADAV AKASH

You should try to use:

您应该尝试使用:

echo "scale=4;$variablename/3"|bc