在Emacs中成语的成语批处理? [英] Idiomatic batch processing of text in Emacs?

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

问题描述

在Python中,您可能会执行以下操作

In Python, you might do something like

fout = open('out','w')
fin = open('in')
for line in fin:
    fout.write(process(line)+"\n")
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:处理文件中获得了灵感(和代码)

which I got inspiration (and code) from Emacs Lisp: Process a File line-by-line. Or should I try something entirely different? And how to remove the "" from the print statement?

推荐答案

如果您确实要批量处理 stdin 并将结果发送到标准输出,则可以使用-script 命令行选项,它将使您能够编写从 stdin 读取并写入的代码 stdout stderr

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 "\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 的文件

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天全站免登陆