user1098798
user1098798

Reputation: 381

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

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?

Upvotes: 3

Views: 629

Answers (3)

ataylor
ataylor

Reputation: 66099

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.

Upvotes: 6

huaiyuan
huaiyuan

Reputation: 26549

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

Upvotes: 2

user507077
user507077

Reputation:

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

Upvotes: 3

Related Questions