smilingbuddha
smilingbuddha

Reputation: 14660

Cutting a text file into multiple parts in Emacs

I am using the GNU Emacs 23 editor. I have this huge text file containing about 10,000 lines which I want to chop into multiple files. Using the mouse to select the required text to paste in another file is the really painful. Also this is prone to errors too.

If I want to divide the text file according to the line numbers into say 4 file where first file:lines 1-2500 second file:lines 2500-5000 third file :lines 5000-7500 fourth file: lines: 7500-10000

how do I do this? At the very least, is there any efficient way to copy large regions of the file just by specifying line numbers

Upvotes: 2

Views: 927

Answers (3)

Drew
Drew

Reputation: 30699

I use this command, from misc-cmds.el (http://www.emacswiki.org/emacs/misc-cmds.el). You just select the text you want and then copy it to the file you want -- see the doc string.


    (defun region-to-file (start end filename arg)
      "With prefix arg, this is `append-to-file'.  Without, it is `write-region'.
    START and END are the region boundaries.
    Prefix ARG non-nil means append region to end of file FILENAME.
    Prefix ARG nil means write region to FILENAME, replacing contents."
      (interactive
       (list (region-beginning) (region-end)
             (read-file-name (concat (if current-prefix-arg "Append" "Write")
                                     " region to file: "))
             current-prefix-arg))
      (let* ((curr-file (buffer-file-name))
             (same-file-p (and curr-file (string= curr-file filename))))
        (cond ((or (not same-file-p)
                   (progn
                     (when (fboundp 'flash-ding) (flash-ding))
                     (yes-or-no-p
                      (format
                       "Do you really want to REPLACE the contents of `%s' by \
    just the REGION? "
                       (file-name-nondirectory curr-file)))))
               (write-region start end filename arg)
               (when same-file-p (revert-buffer t t)))
              (t (message "OK.  Not written.")))))

Upvotes: 1

Optimal Cynic
Optimal Cynic

Reputation: 797

C-u is your friend. Try this:

C-spc (set mark at point)
C-u 2500 <down> (equivalent to pressing the down key 2500 times)
M-w (copy)

Upvotes: 3

psmears
psmears

Reputation: 28030

The following should work:

M-<           (go to start of file)
C-space       (set mark at current cursor position)
ESC 2500 down (go down 2500 lines)
C-w           (delete between mark and cursor, and put it in cut buffer)
...           (open new file, using your favourite method)
C-Y           (paste contents of cut buffer)

Upvotes: 3

Related Questions