3

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.

Lawless Leopard
  • 59
  • 2
  • 10
  • Does this answer your question? [vim let search and replace with increment](https://stackoverflow.com/questions/54398235/vim-let-search-and-replace-with-increment) – phd Nov 18 '20 at 20:19
  • https://stackoverflow.com/search?q=%5Bvim%5D+replace+increment – phd Nov 18 '20 at 20:19

1 Answers1

4

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.

SergioAraujo
  • 11,069
  • 3
  • 50
  • 40
  • This looks good, but shouldn't the ':' be outside the double-quotes in the replacement section of the solution? – DC Slagel Nov 19 '20 at 12:49