1

windows 10, Emacs 26.1

Suppose I has the next text

[
  {
    "id": 1,
    "finished": 1573550444.4444,
    "orgn": 17
  },
  {
    "id": 1,
    "finished": 1573550444.4444,
    "orgn": 17
  },
  {
    "id": 1,
    "finished": 1573550444.4444,
    "orgn": 17
  },
  {
    "id": 1,
    "finished": 1573550444.4444,
    "orgn": 17
  }
]

I need to increment only field "id"

The result must be like this:

[
  {
    "id": 2,
    "finished": 1573550444.4444,
    "orgn": 17
  },
  {
    "id": 3,
    "finished": 1573550444.4444,
    "orgn": 17
  },
  {
    "id": 4,
    "finished": 1573550444.4444,
    "orgn": 17
  },
  {
    "id": 5,
    "finished": 1573550444.4444,
    "orgn": 17
  }
]

Is it possible? Without create my custom function.

  • This sounds like a duplicate (besides the other one that you posted today), but I don't have time now to look for it. – Drew Nov 14 at 20:37
  • @NickD No: replacing by successive integers is not the same thing as replacing by a value constructed from the original value. – Gilles 'SO- stop being evil' Nov 14 at 23:08
  • Cross-referencing with emacs.stackexchange.com/questions/52780/… , which isn't a duplicate, but is sufficiently similar that there are equivalent answers posted in each. – phils Nov 15 at 22:38
  • Also see: emacs.stackexchange.com/questions/37898/…, for another similar question. – zck Nov 17 at 7:09
2

Use a regular expression replacement with a bit of Lisp code. In the replacement text, you can use \,(…) to execute some Lisp code, and you can use \# as the number of replacements made so far. So \,(+ 2 \#) will be become successively 2, 3, 4, … in successive replacements.

Thus, use C-M-% or M-x replace-regexp to replace \("id": \)[0-9]+
with \1\,(+ 2 \#)

0

That should do it:

(defun cummulative-raise-regexp (&optional regexp)
  (interactive)
  (let* ((regexp (or regexp "\"id\": \\([0-9]+\\),"))
     (counter 1))
    (while (re-search-forward regexp nil t)
      (replace-match (concat "\"id\": "(number-to-string (+ counter (string-to-number (match-string-no-properties 1))))","))
      (setq counter (1+ counter)))))

Not the answer you're looking for? Browse other questions tagged or ask your own question.