If you want to replace a regexp in a file (not a buffer which is already open in Emacs, but a file), what would be the fastest and most efficient way?
(I mean, a quick equivalent to sed -i 's/old/new/g' file.txt in Bash.)
For instance, this snippet works, but is quite long for such a simple task:
More generally, most Emacs commands operate on buffers, not on files. When you want to operate on a file, is it canonical to open your file in a temp-buffer, do your operations, and then kill (and save) your buffer? Or is there some better way to proceed?
with-temp-file creates a temp buffer and writes the content of the temp buffer to the specified file. The temp buffer gets killed automatically.
Note that the documentation warns against using replace-regexp in Emacs Lisp, but depending on your use case it could be fine:
This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
(while (re-search-forward REGEXP nil t)
(replace-match TO-STRING nil nil))
which will run faster and will not set the mark or print anything.