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.

a_subscriber
  • 3,854
  • 1
  • 17
  • 47
  • 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 '19 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 '19 at 23:08
  • Cross-referencing with https://emacs.stackexchange.com/questions/52780/replace-placeholder-by-incremental-value , which isn't a duplicate, but is sufficiently similar that there are equivalent answers posted in each. – phils Nov 15 '19 at 22:38
  • Also see: https://emacs.stackexchange.com/questions/37898/incrementally-replace-a-given-string/37899#37899, for another similar question. – zck Nov 17 '19 at 07:09

2 Answers2

3

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)))))
Andreas Röhler
  • 1,894
  • 10
  • 10