班门学艺

醉里且贪欢笑,要愁那得工夫。近来始觉古人书,信着全无是处。 昨夜松边醉倒,问松“我醉何如”。只疑松动要来扶,以手推松曰:“去”!

2009年2月17日星期二

批量更改文件名

批量更改某一个目录下文件名。

;;; rename.el ---
;;Author:QinGW

;;(rename-file "foo" "fool")
;; Thanks Hiroyuki Komatsu . Some functions from his mell-string.el
(defun mell-string-split (string regexp)
"Divide STRING from REGEXP."
(let ((start 0) match-list splited-list)
(while (string-match regexp string start)
(setq match-list
(append match-list (list (match-beginning 0) (match-end 0))))
(setq start (match-end 0))
)
(setq match-list (append '(0) match-list (list (length string))))
(while match-list
(setq splited-list
(cons (substring string (nth 0 match-list) (nth 1 match-list))
splited-list))
(setq match-list (nthcdr 2 match-list))
)
(reverse splited-list)))

(defun mell-string-replace (target-string from-regexp to-string)
"Replace TARGET-STRING from FROM-REGEXP to TO-STRING."
(if (string-match from-regexp target-string)
(setq target-string
(mapconcat '(lambda (x) x)
(mell-string-split target-string from-regexp)
to-string))
)
target-string)
;;batch rename file
;;just eval C-x C-e, I don't extract them into one function.
;;it can implement to change all files of prefix with 'u' into 'U' under current ;;directory
(let
((dirfiles (directory-files "." t "^u")))
(while dirfiles
(setq filename (car dirfiles))
(setq newfilename (mell-string-replace filename "u" "U"))
(print newfilename)
(rename-file filename newfilename)
(setq dirfiles (cdr dirfiles))
))

(length (directory-files "." t "^u"))

(provide 'rename)
;;; rename.el ends here