emacs - Emacs 中文本的惯用批处理?

标签 emacs elisp

在 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 读取的代码并写信给 stdoutstderr .

这是一个示例程序,类似于 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/

相关文章:

emacs - 如何重新绑定(bind)通常绑定(bind)到 C-h 和 <f1> 的 Emacs 帮助键?

lisp - 执行一个函数直到它返回一个 nil,将它的值收集到一个列表中

emacs - Emacs Lisp 的 REPL

emacs - 不一致的 M-x align-regexp 与 C-u M-x align-regexp 行为

sql - 如何创建 Emacs SQL 缓冲区?

Emacs 中的 Scala 模式缩进

emacs - Elisp 在 progn 上使用 apply 函数列表

emacs - 我怎么知道我是在 .emacs 文件中运行 emacs 还是 aquamacs?

html - 在 Emacs 中将语法突出显示的代码转换为 HTML

emacs - AUCTex 问题中的预览