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

Go To StackoverFlow.com

3

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?

2012-04-03 21:40
by user1098798
As an alternative to the dotimes approach, you could also use number-sequence and mapconcat to generate the content for the file as follows: (mapconcat 'number-to-string (number-sequence 1 5) "\n") - phils 2012-04-04 10:27


5

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.

2012-04-03 22:11
by ataylor
Sorry I'm a complete newbie with emacs but where would I write the elisp function? How do you make these kind of functions available within emacs - user1098798 2012-04-04 09:17
Put it in .emacs in your home directory and restart emacs. Or type it into any buffer and run eval-last-sexp (C-x C-e) when the point is just after the final paren. Yet another way is to run eval-expression (M-:) and type it in at the prompt. The last two methods won't persist between emacs sessions - ataylor 2012-04-04 15:08
Fantastic - thank you so much - user1098798 2012-04-05 09:16


3

Why don't you use the shell program seq for it? E.g. seq 20 will print 20 neat lines numbered 1 to 20.

2012-04-03 22:09
by Moritz Bunkus
I have upvoted you but not accepted the answer. Your answer is really useful to know but I am more interested in finding out more about how emacs works so even though it might not be the easiest way to fill a file with line numbers I want to know how to do it with emacs : - user1098798 2012-04-04 09:19


1

M-: (with-temp-file "foo.txt" (dotimes (i 15) (insert (format "%2d\n" (1+ i)))))

If you do this often enough, make it a function:

(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))))))
2012-04-04 09:03
by huaiyuan
Ads