Emacs 中文本的惯用批处理? [英] Idiomatic batch processing of text in Emacs?

查看:16
本文介绍了Emacs 中文本的惯用批处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,你可能会做类似的事情

In Python, you might do something like

fout = open('out','w')
fin = open('in')
for line in fin:
    fout.write(process(line)+"
")
fin.close()
fout.close()

(我认为在许多其他语言中也是相似的).在 Emacs Lisp 中,你会做类似的事情吗

(I think it would be similar in many other languages as well). In Emacs Lisp, would you do something like

(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:逐行处理文件中获得灵感(和代码)行.或者我应该尝试一些完全不同的东西?以及如何从打印语句中删除 "" ?

推荐答案

如果你真的想要批量处理 stdin 并将结果发送到 stdout,你可以使用--script 命令行Emacs 的选项,这将使您能够编写从 stdin 读取并写入 stdoutstderr 的代码.

If you actually want batch processing of stdin and sending the result to stdout, you can use the --script command line option to Emacs, which will enable you to write code that reads from stdin and writes to stdout and stderr.

这是一个示例程序,类似于 cat,除了它反转每一行:

Here is an example program which is like cat, except that it reverses each line:

#!/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 "
")
      ;; (princ "command-line-args is" )
      ;; (princ command-line-args)
      ;; (princ "
")

      (while (setq line (read-from-minibuffer ""))
        (princ (process line))
        (princ "
")))
  (error nil))

现在,如果您有一个名为 stuff.txt 的文件,其中包含

Now, if you had a file named stuff.txt which contained

abcd
1234
xyz

并且您像这样调用了上面编写的 shell 脚本(假设它名为 rcat):

And you invoked the shell script written above like so (assuming it is named rcat):

rcat < stuff.txt

您将看到以下内容打印到标准输出:

you will see the following printed to stdout:

dcba
4321
zyx

因此,与流行的看法相反,您实际上可以在 stdin 上进行批处理文件处理,而实际上不必一次读取整个文件.

So, contrary to popular belief, you can actually do batch file processing on stdin and not actually have to read the entire file in at once.

这篇关于Emacs 中文本的惯用批处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆