1

Windows 10 Emacs 26.1

I has the next text

[
  {
    "id": N,
    "name": "Agent#N",
    "address": "N Tabernacle St, London EC2A 4DD, UK"
  },
  {
    "id": N,
    "name": "Agent#N",
    "address": "N Tabernacle St, London EC2A 4DD, UK"
  },
  {
    "id": N,
    "name": "Agent#N",
    "address": "N Tabernacle St, London EC2A 4DD, UK"
  }
]

I need to replace N in every node by incremental integer value. The result must be like this:

[
  {
    "id": 1,
    "name": "Agent#1",
    "address": "1 Tabernacle St, London EC2A 4DD, UK"
  },
  {
    "id": 2,
    "name": "Agent#2",
    "address": "2 Tabernacle St, London EC2A 4DD, UK"
  },
  {
    "id": 3,
    "name": "Agent#3",
    "address": "3 Tabernacle St, London EC2A 4DD, UK"
  }
]

Is it possible?

3

You could use keyboard macros, but the easiest approach in this case is probably to query-replace-regexp this:

"id": N,
"name": "Agent#N",
"address": "N Tabernacle St, London EC2A 4DD, UK"

with this:

"id": \#,
"name": "Agent#\#",
"address": "\# Tabernacle St, London EC2A 4DD, UK"

The counter is zero-based, so either add a dummy record at the start, or else use \,(1+ \#) instead of plain \#


n.b. There are no regexp-special characters in this text, so nothing needs escaping in the search pattern.

If, however, this is just one example amongst many, then there's a trick you can employ to automatically escape characters in the pattern as necessary:

  • Copy the text to search for.
  • C-M-s to run isearch-forward-regexp.
  • C-y to yank the copied text as the search pattern. Emacs will automatically escape any regexp-special characters.
  • C-M-% to begin a query-replace-regexp for the isearch pattern.
  • C-y to again paste the original copied text, this time as the replacement text.
  • Edit the pasted replacement text to use the \# counter.
  • Submit the replacement text, and begin replacing the matches as required...

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