1

I have a text file that looks like this:

qwerty=1.8
asdfg=15.9
zxcvb=144.99

I managed to replace a specific version with another specific version using sed:

sed s/asdfg=15.9/asdfg=15.10/ file

But how can i make it dynamic? My end goal is a command that i can use with argument "asdfg" and it will update the line asdfg=15.9 to asdfg=15.10 without me having to know the version.

Inian
  • 80,270
  • 14
  • 142
  • 161
Stacky Boy
  • 23
  • 2
  • 2
    please check this url https://stackoverflow.com/questions/14348432/how-to-find-replace-and-increment-a-matched-number-with-sed-awk – amit bhosale Jun 22 '20 at 08:29

1 Answers1

2

With GNU awk:

$ # adds 1 to entire number after =
$ awk 'match($0, /(asdfg=)(.+)/, m){$0 = m[1] m[2]+1} 1' file
qwerty=1.8
asdfg=16.9
zxcvb=144.99

$ # adds 1 after the decimal point
$ awk 'match($0, /(asdfg=[0-9]+\.)(.+)/, m){$0 = m[1] m[2]+1} 1' file
qwerty=1.8
asdfg=15.10
zxcvb=144.99

Here match is used to separate out the prefix string and the number to be incremented. The results are available from m array.



With perl

$ perl -pe 's/asdfg=\K.+/$&+1/e' file
qwerty=1.8
asdfg=16.9
zxcvb=144.99

The e flag allows you to use Perl code in replacement section. \K is used here to avoid asdfg= showing up in matched portion. $& will have the matched portion, which is the number after asdfg= in this case.

To change only after the decimal point:

$ perl -pe 's/asdfg=\d*\.\K.+/$&+1/e' ip.txt
qwerty=1.8
asdfg=15.10
zxcvb=144.99

Use perl -i -pe to write the changes back to file. Use -i.bkp to create backups.

Sundeep
  • 23,246
  • 2
  • 28
  • 103