How would you make emacs write out line numbers into a file?

emacs

Solution

Here's a quick elisp function that does it:

(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"))))

You would run it with `(write-line-numbers 8)` in elisp or with M-x write-line-numbers 8 interactively.

Or you could save the above as a script and run emacs like so:

emacs -Q --script write-line-numbers.el --eval '(write-line-numbers 8)'

But as Moritz points out, there are better ways to do this outside of emacs.

Problem

How would you go about writing a file from emacs that contains only the line numbers eg: ``` 1 2 3 4 5 ``` Ideally this would be a command that you would execute (how?) that can be told how many lines to print. Is this possible?

Original source