Skip to main content

15.10.1 Unconditional Replacement

M-x replace-string RET string RET newstring RET

Replace every occurrence of string with newstring.

To replace every instance of ‘foo’ after point with ‘bar’, use the command M-x replace-string with the two arguments ‘foo’ and ‘bar’. Replacement happens only in the text after point, so if you want to cover the whole buffer you must go to the beginning first. All occurrences up to the end of the buffer are replaced; to limit replacement to part of the buffer, activate the region around that part. When the region is active, replacement is limited to the region (see Mark).

When replace-string exits, it leaves point at the last occurrence replaced. It adds the prior position of point (where the replace-string command was issued) to the mark ring, without activating the mark; use C-u C-SPC to move back there. See Mark Ring.

A prefix argument restricts replacement to matches that are surrounded by word boundaries.

See Replacement and Lax Matches, for details about case-sensitivity and character folding in replace commands.