3

I currently have a single file that has nearly 10000 lines of text in it. Each section that I want is broken up like so -

Chapter 1: Chapter 1
TEXT GOES HERE
Chapter 2: Chapter 2
TEXT GOES HERE
Chapter 3: Chapter 3
TEXT GOES HERE

I want to break up each chapter so that I save a file like 01.tex, 02.tex, and 03.tex that contains all of that text for that chapter. Is there a way to regex through the file and make a save for each chapter?

5

That's a job for :global, with which you can split the file into ranges, here from a line starting with Chapter to the one before the next such line. To correctly handle the last range, insert a dummy line containing EOF at the end first.

To build the filespec, I would usually use :execute, but that doesn't handle ranges. So, I use the more obscure backtick expression (:help `=). Instead of a variable counter, I just grab the first number from the current (first of the range) line:

:global/^Chapter/,/^Chapter\|^EOF/-1write `='path/to/dir' . matchstr(getline('.'), '\d\+') . '.tex'`

This basically searches for all lines starting with Chapter, and then :write the following range: .,/^Chapter\|^EOF/-1 (the . is implicit by the positioning of :global).

  • Could you explain that semicolon? I'd have expected a <kbd>.</kbd> there to denote the current line (which is the line matching ^Chapter), and can't really find out what a semicolon does there (usually, it repeats f,F,t,T, but that doesn't apply here, does it?). Also, couldn't you use %:h instead of path/to/dir? – PhilippFrank Mar 18 '15 at 8:34
  • @PhilippFrank: The semicolon is a range delimiter, see :h :range. It makes the search for the end start at the position of the first part of the range (with :g, it actually doesn't matter, and , would do, too). Yes, %:h would do; the path/to/dir was just an example, obviously. – Ingo Karkat Mar 18 '15 at 8:56
  • Do you think you could explain how it works a bit more detail? I've read :h :global and :h :range, and I understand roughly what's happening, but I'm still having a bit of trouble parsing precisely the boundary between where the "pattern" for the global ends and where the range for the write begins. – Rich Mar 18 '15 at 12:19
  • @Rich: Yes, it's a bit cryptic. I've added some more details! – Ingo Karkat Mar 18 '15 at 13:15
  • It was the implicit . that was stumping me. Thanks! – Rich Mar 18 '15 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.