Linux Shell脚本-读取属性文件并添加(数学)两个变量

Linux Shell脚本-读取属性文件并添加(数学)两个变量,linux,shell,properties,scripting,addition,Linux,Shell,Properties,Scripting,Addition,我正在编写一个在循环上运行的程序,我需要增加作为变量传入的时间毫秒。它是用来计算时间戳的 我发现了如何更改属性文件中的属性,如下所示: sed -i "/exampleKey=/ s/=.*/=newExampleValue1/" test.properties exampleKey=1000 //Get Current value here (1000) sed -i "/exampleKey=/ s/=.*/= (current value + 500) /" test.propert

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

我发现了如何更改属性文件中的属性,如下所示:

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

//Get Current value here (1000)

sed -i "/exampleKey=/ s/=.*/= (current value + 500) /" test.properties
但在此之前,我希望能够获取currentExampleValue1并对其执行加法

像这样:

sed -i "/exampleKey=/ s/=.*/=newExampleValue1/" test.properties
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/=(.*)/"=" . ($1 + 500)/e' test.properties
-p逐行读取文件,并在处理后打印每个文件

/e将替换零件作为代码进行评估

对于较短的代码,可以使用look-behind断言:

s/(?<==)(.*)/$1 + 500/e
i、 e.将前面的所有内容替换为=本身+500。

使用awk,这将是:

awk -F= '$1=="exampleKey"{$2+=500}1'
字段分隔符设置为=字符,因此$2指向要增加的值


如果您有GNU awk,您可能希望使用选项-i inplace直接对文件执行更改,类似于-i for sed。

这非常好。我一直在寻找。。。显然是在错误的地方做这件事。这很好用。非常感谢。您知道如何轻松读取属性文件并获取值吗?例如,newKey=someValue,代码后面的值是$someValue..要问一个新问题,请打开一个新问题:-