如何在Common Lisp中进行批量文件编辑?

4
我希望了解如何在Common Lisp中进行文件批量编辑。我曾经需要这样做并使用了Perl和Bash。出于好奇,我想知道Common Lisp的解决方案。
我使用了以下方法:
find -name '*.lisp' -execdir perl -0777 -pi.bak -e 's/foo/bar/mi' '{}' '+'

它起到了事半功倍的效果。

以上命令将目录中的所有文件(及其子目录)传递给一个perl程序。Perl程序搜索正则表达式“foo”并用正则表达式“bar”替换它,然后在原地保存新的(编辑后)文件。

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


1
Unix 命令行是一种很好的方法,但如果你必须使用 Lisp,请查看手册中的 mapcardirectorywith-open-fileread-charread-linewrite-charwrite-linereplace 函数。手册地址:http://www.lispworks.com/documentation/HyperSpec/Front/。 - John Pick
2
你可能想使用简单的词语来解释上面一行代码的作用,不要假设每个人都知道。 - Rainer Joswig
2个回答

2

1

你可以使用 sbcl --noinform --quit --eval 代替 perl

至于脚本内容,类似以下的代码应该可以工作:

(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")))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接