Write a command to do find and replace all files in a dir, and a command to undo it
write a command to do find and replace, all files in a dir.
and a command to undo it.
(defvarxx-find-replace-last-recordnil"
A list, like this
(‹full-path-of-dir› ‹timestamp-string›)
both are strings.")
(defunxx-find-replace
(FindStringRelpaceStringRootdirFinenameExtRegex)
"Find and replace all files in a dir.
Created: 2024-09-12
Version: 2024-09-12"
(interactive)
(let (xfilelist
(xbackupTimestamp (format-time-string"~xfp%Y%m%d_%H%M%S~")))
;; algo
;; get a list of files in root dir
;; for each, open it, do find and replace
;; make a backup
(setqxfilelist
(directory-files-recursivelyRootdirFinenameExtRegexnil
(lambda (x) (not (string-match-p"/\\."x)))))
;; open each file
(mapc
(lambda (xfpath)
(let (xfound-p)
(with-temp-buffer
(insert-file-contentsxfpath)
;; do find replace
(goto-char (point-min))
(while (search-forwardFindStringnilt)
(replace-matchRelpaceStringtt)
(setqxfound-pt))
(whenxfound-p;; backup
(setqxx-find-replace-last-record (listRootdirxbackupTimestamp))
(copy-filexfpath (concatxfpathxbackupTimestamp) t)
;; save
(write-region (point-min) (point-max) xfpath)))))
xfilelist)))
;; HHHH---------------------------------------------------
(defunxx-find-replace-undo-last ()
"Undo last call of `xx-find-replace'
Created: 2024-09-12
Version: 2024-09-12"
(interactive)
(let (xfilelistxrootdirxtimestamp)
;; first we need is to get the unique timestamped file names
;; and the root dir
;; then, get a list of such file names
;; foreach, just rename the original with it.
(setqxrootdir (nth 0 xx-find-replace-last-record))
(setqxtimestamp (nth 1 xx-find-replace-last-record))
(setqxfilelist
(directory-files-recursivelyxrootdir (regexp-quotextimestamp)
nil
(lambda (x) (not (string-match-p"/\\."x)))))
(mapc
(lambda (x)
(let (xorig-name)
;; Abbrev-Expansion.html~2024-09-12_131822_xf~
(setqxorig-name (substringx 0 (string-match"~"x)))
(rename-filexxorig-namet)))
xfilelist)))
;; HHHH---------------------------------------------------
;; test
(xx-find-replace"Manual""xmm""c:/Users/xah/web/xahlee_info/talk_show/xxtest/elisp/elisp/""\\.html$"
)
(xx-find-replace-undo-last)