bash 在 shell 脚本中减去字符串(即数字)

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

Subtracting strings (that are numbers) in a shell script

bashshellmath

提问by hao_maike

I made a shell script that finds the size of a directory, returning it in human readable format (e.g., 802M or 702K). I want to calculate the difference between the sizes.

我制作了一个 shell 脚本来查找目录的大小,并以人类可读的格式(例如,802M 或 702K)返回它。我想计算尺寸之间的差异。

Here's my shell script so far:

到目前为止,这是我的 shell 脚本:

#!/bin/bash

current_remote_dir_size=789M
new_remote_dir_size=802M
new_size=`echo ${new_remote_dir_size} | grep -o [0-9]*`
current_size=`echo ${current_remote_dir_size} | grep -o [0-9]*`

echo "${new_size}-${current_size}"

But the output of the script is just

但是脚本的输出只是

-

How can I make the subtraction work?

我怎样才能使减法工作?

回答by Daniel Beck

You can do basic integer math in bash by wrapping the expression in $((and )).

您可以通过将表达式包装在$((和 中来在 bash 中进行基本的整数数学运算))

$ echo $(( 5 + 8 ))
13

In your specific case, the following works for me:

在您的具体情况下,以下内容对我有用:

$ echo "${new_size}-${current_size}"
802-789
$ echo $(( ${new_size}-${current_size} ))
13

Your output at the end is a bit odd. Check that the grep expression actually produces the desired output. If not, you might need to wrap the regular expression in quotation marks.

你最后的输出有点奇怪。检查 grep 表达式是否实际产生了所需的输出。如果没有,您可能需要将正则表达式用引号括起来。

回答by glenn Hymanman

You don't need to call out to grep to strip letters from your strings:

您无需调用 grep 即可从字符串中删除字母:

current_remote_dir_size=789M
current_size=${current_remote_dir_size%[A-Z]}
echo $current_size  # ==> 789

new_remote_dir_size=802M
new_size=${new_remote_dir_size%[A-Z]}
echo $new_size      # ==> 802

See Shell Parameter Expansionin the bash manual.

请参阅bash 手册中的Shell 参数扩展

回答by user unknown

All you need is:

所有你需要的是:

echo $((${new_remote_dir_size/M/}-${current_remote_dir_size/M/}))
  • $((a+b - 4)) can be used for arithmetic expressions
  • ${string/M/} replaces M in string with nothing. See man bash, Section String substitution, for more possibilities and details.
  • $((a+b - 4)) 可用于算术表达式
  • ${string/M/} 将字符串中的 M 替换为空。有关man bash更多可能性和详细信息,请参阅部分字符串替换。