在 Python 中,你可能会做类似的事情
fout = open('out','w')
fin = open('in')
for line in fin:
fout.write(process(line)+"\n")
fin.close()
fout.close()
(我认为它在许多其他语言中也是相似的)。
在 Emacs Lisp 中,你会做类似的事情吗?
(find-file 'out')
(setq fout (current-buffer)
(find-file 'in')
(setq fin (current-buffer)
(while moreLines
(setq begin (point))
(move-end-of-line 1)
(setq line (buffer-substring-no-properties begin (point))
;; maybe
(print (process line) fout)
;; or
(save-excursion
(set-buffer fout)
(insert (process line)))
(setq moreLines (= 0 (forward-line 1))))
(kill-buffer fin)
(kill-buffer fout)
我从 Emacs Lisp: Process a File line-by-line 获得灵感(和代码) .或者我应该尝试一些完全不同的东西?以及如何删除
""
从打印声明?
最佳答案
如果你真的想要批量处理 stdin
并将结果发送到 stdout
,您可以使用 --script Emacs 的命令行选项,这将使您能够编写从 stdin
读取的代码并写信给 stdout
和 stderr
.
这是一个示例程序,类似于 cat
,除了它反转每一行:
#!/usr/local/bin/emacs --script
;;-*- mode: emacs-lisp;-*-
(defun process (string)
"just reverse the string"
(concat (nreverse (string-to-list string))))
(condition-case nil
(let (line)
;; commented out b/c not relevant for `cat`, but potentially useful
;; (princ "argv is ")
;; (princ argv)
;; (princ "\n")
;; (princ "command-line-args is" )
;; (princ command-line-args)
;; (princ "\n")
(while (setq line (read-from-minibuffer ""))
(princ (process line))
(princ "\n")))
(error nil))
现在,如果您有一个名为
stuff.txt
的文件其中包含abcd
1234
xyz
并且您像这样调用了上面编写的 shell 脚本(假设它被命名为
rcat
):rcat < stuff.txt
您将看到以下内容打印到标准输出:
dcba
4321
zyx
因此,与流行的看法相反,您实际上可以在
stdin
上进行批处理文件处理。而实际上不必一次读取整个文件。
关于emacs - Emacs 中文本的惯用批处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2879746/