简体   繁体   English

使用sed替换字符串中的版本号

[英]Replace version number in a string using sed

I have a bundle version set in a file, like this: 我在文件中设置了捆绑版本,如下所示:

"dist/app-build-v1.08": {

How can I sed the version number and swap it out with an incremented number? 如何查找版本号并以递增的数字换出?

First I'm attempting to grab the line itself, which is the third line in my bundle file. 首先,我试图抓住线本身,这是我的捆绑文件中的第三行。

BUILD=$(sed '3q;d' ./build/bundles.js)

Which does indeed grab the line. 这确实抓住了这条线。 I found this snippet here on stack overflow: 我在堆栈溢出时发现了这个片段:

's/[^0-9.]*\([0-9.]*\).*/\1/'

Which i'd like to use on $BUILD, but it doesn't work. 我想在$ BUILD上使用它,但它不起作用。 The expected output for me would be 我的预期输出是

$NUM = "1.08"

Then I'd like increment it to 1.09, rebuild the string and used sed -i to replace it. 然后我想将它增加到1.09,重建字符串并使用sed -i替换它。

It seems that the interesting line is always line 3. Then you can use this awk one-liner: 似乎有趣的线总是第3行。然后你可以使用这个awk单线:

awk 'NR==3{gsub(/[^.0-9]+/,"");$0+=0.01;print}' file.js
  • This line focuses on line3, and take the version number, add 0.01 to it. 这一行侧重于第3行,并取版本号,加上0.01
  • Assume that your version format is always x.xx . 假设您的版本格式始终为x.xx If it is not in this case, it is also possible to calculate the increment dynamically. 如果不是这种情况,也可以动态计算增量。 like 0.01 or 0.00001 But extra implementation is required. 0.01 or 0.00001但需要额外的实施。
  • If you run it with your example file, it will give you 1.09 如果您使用示例文件运行它,它将为您提供1.09

Another way : 其他方式 :

sed -r '3s/.*build-v([0-9]+(\.[0-9]+)?).*/\1+0.01/' | bc -q

Example: 例:

$ echo '"dist/app-build-v1.08": {' | sed -r 's/.*build-v([0-9]+(\.[0-9]+)?).*/\1+0.01/' | bc -q
1.09

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM