我正在尝试编写一个小的Emacs Lisp脚本,它从标准输入读取csv文件,将所有行转换为表格,然后将其打印到标准输出(Unix)。我写了一个基本版本,它接受一个csv字符串并将表输出到缓冲区。但是,我想把它变成一个Unix实用程序脚本。
#!/usr/bin/emacs --script (defun gen-row (lst) (dolist (elm lst) (insert "<tr>") (insert (concat "<td>" elm "</td>")) (insert "</tr>") ) ) (defun parse-csv-line (txt) (setq lst (progn (insert "\n<table>\n") (setq str txt) (gen-row (split-string str ",")) (insert "\n</table>\n") )) ) (parse-csv-line "this,is,a test")
从Emacs中运行时到当前缓冲区的输出:
<table> <tr><td>this</td></tr><tr><td>is</td></tr><tr><td>a test</td></tr> </table>
脚本的用法:
./csv2html < foo.csv > bar.html; # emacs --script instead of perl -ane '...'
答案 0 :(得分:2)
以下是我如何包装你的例程以获得你想要的东西。
注意:我确实将例程更改为princ
字符串,而不是将它们插入缓冲区。
#!/usr/local/bin/emacs --script
(require 'cl)
(defun gen-row (lst)
(mapcar (lambda (elm)
(princ (concat "<tr><td>" elm "</td></tr>")))
lst))
(defun parse-csv-line (txt)
(princ "\n<table>\n")
(gen-row (split-string txt ","))
(princ "\n</table>\n"))
; (parse-csv-line "this,is,a test")
(defun run-it (&optional argv)
(with-temp-buffer
(if argv
(find-file (car argv))
(condition-case nil
(let ((line (read-from-minibuffer "")))
(while line
(insert line)
(insert "\n")
(setq line (read-from-minibuffer ""))))
(error nil)))
;; the current buffer has the file contents (or stdin contents)
;; now process each line
(goto-char (point-min))
(while (< (point) (point-max))
(parse-csv-line (buffer-substring (point) (progn (end-of-line) (point))))
(forward-line 1)
(beginning-of-line 1))))
(run-it argv)
如果您要对表进行更多的处理,可能更容易将输入作为列表进行操作以获得所需内容,然后使用xmlgen
包生成所有HTML标记。 / p>