Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace version number in a string using sed

Tags:

linux

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. 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.

like image 429
Unit43.dev Avatar asked Jun 09 '16 13:06

Unit43.dev


People also ask

How do I change a number using sed?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you use sed to replace the first occurrence in a file?

With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.

Does sed modify files?

There is a huge pool of commands available for Ubuntu and sed command utility is one of them; the sed command can be used to perform fundamental operations on text files like editing, deleting text inside a file.


2 Answers

It seems that the interesting line is always line 3. Then you can use this awk one-liner:

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.
  • Assume that your version format is always 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.
  • If you run it with your example file, it will give you 1.09
like image 82
Kent Avatar answered Oct 16 '22 18:10

Kent


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
like image 33
sat Avatar answered Oct 16 '22 18:10

sat