如何在常见的lisp中进行批量文件编辑?

时间:2012-03-11 22:55:47

标签: file common-lisp

我想知道如何在常见的lisp中批量编辑文件。我需要这一段时间,并使用perl和bash。我想知道普通的lisp解决方案是出于好奇。

我使用了以下内容:

find -name '*.lisp' -execdir perl -0777 -pi.bak -e 's/foo/bar/mi' '{}' '+'

它就像一个魅力。

上面的命令将目录(及其子目录)中的所有文件都提供给perl程序。 perl程序搜索正则表达式“foo”并用正则表达式“bar”替换它,然后将新的(编辑过的)文件保存到位。

感谢您提供有关CL解决方案的任何指导。

2 个答案:

答案 0 :(得分:2)

如何用walk-directoryslurp fileclose the filereplace foo开始吧,将内容写回来,然后......休息。 ; - )

答案 1 :(得分:1)

而不是perl,您可以使用sbcl --noinform --quit --eval

至于脚本内容,这样的事情应该有效:

(progn
  (require :cl-ppcre)

  (let* ((file (nth 4 *posix-argv*))
         (buf (make-array (file-length file)
                          :element-type 'character :adjustable t :fill-pointer t)))
    (setf (fill-pointer buf) (with-open-file (in file)
                               (read-sequence buf in)))
    (princ (ppcre:regex-replace-all "foo" buf "bar"))))

或者,如果您可以逐行提供文件:

(progn
  (require :cl-ppcre)
  (princ (ppcre:regex-replace-all "foo" (read-line) "bar")))