Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cassandra/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 在Shell中,如何对字符串中的数字进行算术运算?_Linux_Shell_Unix_Awk_Sh - Fatal编程技术网

Linux 在Shell中,如何对字符串中的数字进行算术运算?

Linux 在Shell中,如何对字符串中的数字进行算术运算?,linux,shell,unix,awk,sh,Linux,Shell,Unix,Awk,Sh,我想在插入中增加100美元,在下面尝试过,但它却增加了1美元 #!/bin/bash change_summary="17 files changed, 441 insertions(+), 49 deletions(-)" lines_added="100" echo $change_summary echo $change_summary | awk '{ print $1 " " $2 " " $3 " " $4+$lines_added " " $5 " " $6 " " $7}' 它

我想在插入中增加100美元,在下面尝试过,但它却增加了1美元

#!/bin/bash
change_summary="17 files changed, 441 insertions(+), 49 deletions(-)"
lines_added="100"
echo $change_summary
echo $change_summary | awk '{ print $1 " " $2 " " $3 " " $4+$lines_added " " $5 " " $6 " " $7}'
它打印

17 files changed, 441 insertions(+), 49 deletions(-)
17 files changed, 458 insertions(+), 49 deletions(-)
我希望它能打印541个插入

还有更好的方法吗?

您应该“取消引用”添加的
$lines\u

~$ echo $change_summary | awk '{ print $1 " " $2 " " $3 " " ($4)+'$lines_added' " " $5 " " $6 " " $7}'
`17 files changed, 541 insertions(+), 49 deletions(-)
因为它是bash变量,而不是awk变量。

使用awk变量(使用GNU awk测试):

或者更简洁地说:

 $ echo $change_summary | awk -v l=$lines_added '{ $4 += l; print}'
 17 files changed, 541 insertions(+), 49 deletions(-)

太好了,谢谢,有更好的方法吗?或者我正在做的是好的?我不认为有正确的方法,但是正如@Jens指出的,你可以通过-v选项传递变量,我正在使用你的第二个命令,我还需要将数字添加到$6,我尝试了
echo$change\u summary | awk-vl=$lines\u added d=$lines\u deleted'{$4+=l$6+=d;print}'
它抛出了错误,显然我犯了一些错误。有什么帮助吗?非常感谢。@Krish您需要对每个变量使用
-v
awk-va=x-vb=y…
以及每个
$x+=y
语句之间的分号。很好!注意说
打印$1“$2
等有点不必要。只需说
print$1,$2
,因为默认的输出字段分隔符是空格。
 $ echo $change_summary | awk -v l=$lines_added '{ $4 += l; print}'
 17 files changed, 541 insertions(+), 49 deletions(-)