Lawless Leopard
Lawless Leopard

Reputation: 69

Search and replace with increment in 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.

Upvotes: 3

Views: 168

Answers (1)

SergioAraujo
SergioAraujo

Reputation: 11800

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.

Upvotes: 4

Related Questions