Home > Software design >  Finding a string with sed, then replacing a number within that string with incremented number
Finding a string with sed, then replacing a number within that string with incremented number

Time:11-15

I have a file that contains somehting like this:

[project]
name = "sinntelligence"
version = "1.1.dev12"
dependencies = [
  "opencv-python",
  "matplotlib",
  "PySide6",
  "numpy",
  "numba"
]

Now I want to find the "version" string and increment the last number after "dev". Thus in the above example I would like to change

version = "1.1.dev12"

to

version = "1.1.dev13"

and so forth. With grep I was able to get this line with this regular expression:

grep -P "^version.*dev[0-9] "

But since I want to replace something in a file I thought it would make more sense to use sed instead. However, with sed I don't even find that line (i.e. nothing is replaced) with this:

sed -i "s/^version.*dev[0-9] /test/g" sed-test.txt 

Any ideas 1) what I am doing wrong here with sed and 2) how can increase that "dev" number by one and write that back to the file (with just typical Ubuntu Linux command line tools)?

CodePudding user response:

You used grep with -P option that enables the PCRE regex engine, and with sed you are using a POSIX BRE pattern. That is why you do not even match that line.

Then, with sed, you won't be able to easily eval and change the number, you can do that with perl:

perl -i -pe 's/^version.*dev\K(\d )/$1   1/e' sed-test.txt

See the online demo:

#!/bin/bash
s='[project]
name = "sinntelligence"
version = "1.1.dev12"
dependencies = [
  "opencv-python",
  "matplotlib",
  "PySide6",
  "numpy",
  "numba"
]'
perl -pe 's/^version.*dev\K(\d )/$1   1/e' <<< "$s"

Output:

[project]
name = "sinntelligence"
version = "1.1.dev13"
dependencies = [
  "opencv-python",
  "matplotlib",
  "PySide6",
  "numpy",
  "numba"
]

CodePudding user response:

what I am doing wrong here with sed

You have to use -E option to enable extended regular expressions:

$ sed -E  "s/^version.*dev[0-9] /test/g" sed-test.txt
[project]
name = "sinntelligence"
test"
dependencies = [
  "opencv-python",
  "matplotlib",
  "PySide6",
  "numpy",
  "numba"
]

how can increase that "dev" number by one and write that back to the file (with just typical Ubuntu Linux command line tools)?

I'd use awk, below is the adaptation of solution in this Ed Morton's answer:

awk -i inplace '/^version/ {split($3,lets,/[0-9] "$/,digs); $3=lets[1] digs[1] 1 "\""} 1' sed-test.txt
  • Related