你如何在emacs中写一个只包含行数的文件呢?例如:
理想情况下,您可以执行一个命令(如何执行?),并告诉它要打印多少行。这是可能的吗?
1
2
3
4
5
理想情况下,您可以执行一个命令(如何执行?),并告诉它要打印多少行。这是可能的吗?
1
2
3
4
5
(defun write-line-numbers (n)
(interactive "nNumber of lines: ")
(save-excursion
(with-output-to-temp-buffer "*lines*"
(dotimes (line n)
(princ (format "%d\n" (1+ line))))
(set-buffer "*lines*")
(write-file "lines.txt"))))
(write-line-numbers 8)
运行它,也可以通过交互式方式使用M-x write-line-numbers 8来运行。emacs -Q --script write-line-numbers.el --eval '(write-line-numbers 8)'
但是正如Moritz所指出的,除了emacs之外还有更好的方法来完成这个任务。
.emacs
文件中并重新启动emacs。或者在任何缓冲区中输入它,并在光标位于最后一个括号之后时运行eval-last-sexp
(C-x C-e
)。另一种方法是运行eval-expression
(M-:
)并在提示符处键入它。后两种方法不会在emacs会话之间持久保存。 - ataylor为什么不使用shell程序seq
呢?例如:seq 20
将打印出20个整洁的行,编号从1到20。
M-: (with-temp-file "foo.txt" (dotimes (i 15) (insert (format "%2d\n" (1+ i)))))
如果您经常这样做,请将其封装为一个函数:
(defun write-sequence (length output-file)
(interactive "nLength of sequence: \nFOutput file: ")
(with-temp-file output-file
(dotimes (i length) (insert (format "%d\n" (1+ i))))))
(mapconcat 'number-to-string (number-sequence 1 5) "\n")
。 - phils