Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search and replace with increment in vim

Tags:

vim

I have a json file which looks as follows:

{
        "pk": 1,
        "model": "model.Model",
        "fields": {
         "data1": "example",
         "data2": "example"
      }
    },
   {
        "pk": 1,
        "model": "model.Model",
        "fields": {
         "data1": "example",
         "data2": "example"
      }
    },
   {
        "pk": 1,
        "model": "model.Model",
        "fields": {
         "data1": "example",
         "data2": "example"
      }
    },

etc....

I would like to search and replace "pk": 1 and increment the value. so my file would look like:

{
        "pk": 1,
        "model": "model.Model",
        "fields": {
         "data1": "example",
         "data2": "example"
      }
    },
   {
        "pk": 2,
        "model": "model.Model",
        "fields": {
         "data1": "example",
         "data2": "example"
      }
    },
   {
        "pk": 3,
        "model": "model.Model",
        "fields": {
         "data1": "example",
         "data2": "example"
      }
    },

So far I have tried:

:let i=1 | g/"pk": 1/s//="pk": .i./ | let i=i+1

to search for the "pk": 1 pattern and replace it using a counter, but I have a syntax error somewhere and am hitting a brick wall.

Any help / suggestions would be very much appreciated thanks.

like image 786
Lawless Leopard Avatar asked Nov 29 '25 06:11

Lawless Leopard


1 Answers

You could try:

:let i=1 | g/"pk": \zs\d\+/ s//\=i/ | let i+=1

 \zs .............. start pattern

To fix your attempt do:

:let i=1 | g/"pk": 1/s//\='"pk": ' .i/ | let i=i+1

As you can see the first mistake was a missing backslash at the substitution portion \=. The second was using a second concatenation at the end . which would make vim try to concatenate the variable with nothing. The third was forgetting to put the "pk": into 'single quotes' otherwise you would ended up with pk unquoted. Remember here we are concatenating a string with a number.

like image 75
SergioAraujo Avatar answered Dec 02 '25 04:12

SergioAraujo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!