如何使用elisp处理一系列文件? [英] How to process a series of files with elisp?
问题描述
我有一个名为foo01.txt, foo02.txt等,还有一个名为 MyFunction
的函数。我要打开每个文件作为缓冲区,运行 MyFunction
,将缓冲区写入其文件,杀死缓冲区并移动到系列中的下一个文件,直到所有文件完成。
我认为所有需要做的事情都在Cookbook中描述( http://emacswiki.org/emacs/ElispCookbook ),但我并不真正理解如何把它放在一起。谢谢!
答案
如果你正在寻找回答纯粹的elisp,你可以这样做:
(defun process-file(f)
(写入文件f)
(kill-buffer(current-buffer))
(写入文件f)
(find-file f)
(my-function) ))
(defun process-files(dir)
(mapc'process-file
(directory-files dir t.txt $)))
进程文件
将遍历给定的每个文件目录,并将 process-file
应用于所有.txt文件。您可以这样调用:
(进程文件〜/ target-directory)
您可以将其复制到* scratch *缓冲区中,并与各个零件一起玩耍。最有趣的功能是:
-
mapc
- 对每个项目应用一个函数列表 -
目录文件
- 获取目录中的所有文件和文件夹,在这种情况下检索所有.txt文件 -
find-file
- 在缓冲区中打开一个文件(这是当您键入Cx Cf
)
学习Lisp
如果您为了自己的缘故学习Lisp,我可以推荐 实用常用口齿不清 。您将能够使用Elisp来完成令人惊奇的数量的书籍。否则,请下载常见的Lisp环境,例如 SBCL 。
I'm a newbie to programming, so please bear with me here...
I have a directory full of files called "foo01.txt", "foo02.txt", etc. and a function called MyFunction
. I want to open each file as a buffer, run MyFunction
on it, write the buffer to its file, kill the buffer and move on to the next file in the series until all the files are done.
I think all the pieces I need to do this are described in the Cookbook (http://emacswiki.org/emacs/ElispCookbook) but I'm not really understanding how to put it all together. Thanks!
Answer
If you're looking for an answer in pure elisp, you could do something like this:
(defun process-file (f)
(save-excursion
(find-file f)
(my-function) ; Call your function here.
(write-file f)
(kill-buffer (current-buffer))))
(defun process-files (dir)
(mapc 'process-file
(directory-files dir t ".txt$")))
process-files
will iterate over each file in a given directory and apply process-file
to all .txt files. You can call it like so:
(process-files "~/target-directory")
You can copy this into a *scratch* buffer and play around with the individual parts. The most interesting functions are:
mapc
- applies a function to each item in a listdirectory-files
- gets all files and folders in a directory, in this case retrieving all .txt filesfind-file
- opens a file in a buffer (this is what is run when you typeC-x C-f
)
Learning Lisp
If you're learning Lisp for its own sake, I can recommend Practical Common Lisp. You'll be able to work through a surprising amount of the book using Elisp. Otherwise, download a Common Lisp environment like SBCL.
这篇关于如何使用elisp处理一系列文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!