ldward
ldward

Reputation: 73

Script to increment number in a file

I have one file like below,let say file name is file1.txt:

s.version      = "11.7.10"

Here I have to increment the last number by 1, so it should be 1+1=2 like..

s.version      = "11.7.11"

Is there any way for this. Thanks in advance.

Upvotes: 2

Views: 1204

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207385

I would go with Perl, as follows:

perl -pe '/s.version/ && s/(\d+)(")/$1+1 . $2/e' file.txt

That says... "On any line where you find "s.version", substitute the last one or more digits followed by a double quote, with whatever those digits were plus one and the double quote"

So, if your file contains this:

fred
s.version      = "11.7.10"
s.version      = "11.7"
s.version="12.99.99"
frog

You will get this:

fred
s.version      = "11.7.11"
s.version      = "11.8"
s.version="12.99.100"
frog

If you want Perl to edit the file in-place (i.e. overwrite the input file), you can use the -i option:

perl -i.orig -pe '/s.version/ && s/(\d+)(")/$1+1 . $2/e' file.txt

and then your input file will be overwritten, but a backup saved in file.txt.orig

Upvotes: 3

Related Questions