Here are two apporaches one uses only emacs, and the other also uses shell.
In both cases it is usefull to separate the problem in two:
- write a defun which process a single file
- get the list of files and apply the defun to each file
Also I wouldn't insert the file contents in the temp buffer. I would open the file, process it, and the save it -- so that I only need file name once.
A. Using Lisp only
A.1. defun which process a single file
(defun my-process-file (fpath)
"process the file at fullpath FPATH ..."
(let (mybuffer)
(setq mybuffer (find-file fpath))
(goto-char (point-min)) ;; in case buffer is open
(while (search-forward-regexp "REGEXP" nil t)
(replace-match "SUBSTITUTION" nil t)) ;; if you need to reference things like (string-match 1) use: t nil
(save-buffer)
(kill-buffer mybuffer)))
A.2. process files
Do:
(require 'find-lisp)
(mapc 'my-process-file (find-lisp-find-files "/path/to/dir/" "\\.xml$"))
B. Using shell + elisp
B.1. script which process a single file
Make the following shell script my-process-file.bash
:
#! /bin/sh
":"; exec emacs --no-site-file --script "$0" -- "$@" # -*- mode:emacs-lisp -*-
;; emacs options:
(setq make-backup-files nil)
(setq next-line-add-newlines nil)
;; open file:
(find-file (nth 1 argv))
;; process file:
(goto-char (point-min))
(while (search-forward-regexp "REGEXP" nil t)
(replace-match "SUBSTITUTION" nil t)) ;; if you need to reference things like (string-match 1) use: t nil
;; save file:
(save-buffer)
(do not alter first two lines)
B.2. command to process files
Apply it to xml files:
find . -type f -name "*.xml" | parallel my-process-file.bash {}
edit
button in your question and you'll see. ;-) – Malabarba Mar 19 '15 at 13:09