4

I have a json file that I ran a find and replace in using vim, however I forgot a , at the end of the line.

...
"id":41483
"someName":"someValue",
...

Using vim, how can I append a , to every line matching \"id\"\:[0-9].*$?

Matt Clark
  • 27,671
  • 19
  • 68
  • 123

2 Answers2

6

Try this. Match everything that has id followed by any character till the end. Replace it with the matching group (matched by parentheses) which in the replace segment is represented by \1.

%s/\(id".*\)$/\1,/g
ronakg
  • 4,038
  • 21
  • 46
Nikhil Baliga
  • 1,339
  • 12
  • 18
4

Another way to do this is with a global command and the normal command.

:g/"id":[0-9]/norm A,

The global command runs norm A, on every line that matches "id":[0-9]. norm A, runs A, in normal mode which is append a , at the end of the line.

Take a look at :help :global and :h :normal

FDinoff
  • 30,689
  • 5
  • 75
  • 96
  • But what about the capturing group? When adding a `\1` to the appended text it gets appended literally. – radlan Apr 17 '20 at 13:42
  • @radlan there is no capture group here? – FDinoff Apr 17 '20 at 17:07
  • not in your example (and in fact not in the original question). But if the regex contains a capturing group I would expect I can use it for the appended text. – radlan Apr 18 '20 at 19:54
  • @radlan you would need to use the answer in https://stackoverflow.com/a/36608336/1890567 instead. I don't think global can have capture groups. – FDinoff Apr 19 '20 at 16:50