Shell 脚本 - 读取属性文件和两个变量的加法(数学)

Shell Scripting - Reading properties file and Addition (mathematical) of two variables

我正在编写一个将在循环上运行的程序,我需要增加作为变量传入的时间毫秒数。它用于时间戳计算。

我发现了如何像这样更改属性文件中的属性:

sed -i "/exampleKey=/ s/=.*/=newExampleValue1/" test.properties

但在此之前我希望能够获取 currentExampleValue1 并对其执行加法..

像这样:

exampleKey=1000

//Get Current value here (1000)

sed -i "/exampleKey=/ s/=.*/= (current value + 500) /" test.properties

因此属性文件现在是:

exampleKey=1500

在 Linux 中有没有简单的方法可以做到这一点?我应该指出,我对 shell 脚本编写非常陌生。

sed 不会做数学。 Perl 可以:

perl -i~ -pe '/exampleKey=/ and s/=(.*)/"=" . ( + 500)/e' test.properties
  • -p逐行读取文件,处理后逐行打印

  • /e 将替换部分评估为代码。

您可以对更短的代码使用回顾断言:

s/(?<==)(.*)/ + 500/e

即将 = 前面的所有内容替换为自身 + 500.

使用 awk,这将是:

awk -F= '=="exampleKey"{+=500}1'

字段分隔符设置为=字符,这样</code>指向您要增加的值。</p> <p>如果您有 GNU awk,您可能希望使用选项 <code>-i inplace 直接对文件执行更改(类似于 sed 的 -i)。