skip to Main Content

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)?

2

Answers


  1. 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.*devK(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.*devK(d+)/$1 + 1/e' <<< "$s"
    

    Output:

    [project]
    name = "sinntelligence"
    version = "1.1.dev13"
    dependencies = [
      "opencv-python",
      "matplotlib",
      "PySide6",
      "numpy",
      "numba"
    ]
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search