Search code examples
awkgrepincrement

Increase number delimited with dots from params file


I have few params in my params.txt

config_version = "1.2.3" 

test_version = "1.2.3" 

version_count = "1.2.3" 

service_name = "test"

already have answer from this forum how to get this number as output:

awk 'BEGIN{FS="[ \"]+"}/config_version =/{print $3}' /dir/params.txt

I need to increase number of config_version value +1 for each awk one liner run. Examples:

first value is 1.2.3, after awk command run --> 1.2.4 and save back to file

first value is 1.200.1, after awk command run --> 1.200.2 and save back to file

first values is 8.999.99, after awk command run --> 9.000.0 and save back to file

after each run of awk command the params.txt config_version will be updated to increased value

params.txt after 5 awk script execution:

config_version = "1.2.8" 

test_version = "1.2.3" 

version_count = "1.2.3" 

service_name = "test"

It all runs on Gitlab CI and only one-liner will be the option I can use.

"Gitlab job run (1) -> take 1.200.0 -> change to 1.200.1"

"Gitlab job run (2) -> take 1.200.1 -> change to 1.200.2"

"Gitlab job run (10) -> take 1.200.9 -> change to 1.201.0"

"Gitlab job run (xx) -> take 1.999.9 -> change to 2.000.0"

Command will run as a one liner in gitlab ci


Solution

  • $ cat version.txt
    1.2.3
    $ awk -F. 'BEGIN{ OFS="." }{ $3++; if ($3>9){ $2++; $3=0 }; print $1,$2,$3 }' version.txt
    1.2.4
    

    Now I should explain this code, but it's to simple to explain. 😕😉

    EDIT:

    • this looks for "config_version"
    • this uses gawk
    • this is a one-liner
    awk 'BEGIN{ OFS="." }/config_version/{match($0,/([0-9]+)+.([0-9]+)+.([0-9])+/,a); a[3]++; if(a[3]>9) { a[3]=0; a[2]++ }; if(a[2]>999){ a[2]=0; a[1]++ }; print "config_version = \"" a[1],a[2],a[3]"\""}!/config_version/'  version.txt > version.tmp; cp version.tmp version.txt
    

    or (just for better readability)

    awk 'BEGIN{ OFS="." }
         /config_version/{match($0,/([0-9]+)+.([0-9]+)+.([0-9])+/,a);
           a[3]++; 
           if(a[3]>9) { a[3]=0; a[2]++ }; 
           if(a[2]>999){ a[2]=0; a[1]++ }; 
           print "config_version = \"" a[1],a[2],a[3]"\""}
         !/config_version/'  version.txt > version.tmp; cp version.tmp version.txt
    
    • lines match config_version will be matched, and incremented
    • lines match config_version will be copied without change
    • output is send to version.tmp. If you use version.txt as output you will be left with a zero byte length file..