I have a file that contains a story. I need to split the file in a way that each chapter (chapter starts with the word 'chapter') will be in diffrent directory.

CHAPTER count as- everything that appears after the word 'CHAPTER' (like that). so every time that this word appears evertything after that till the next 'chapter' needs to move to new directory. I need to create the directories, they don't exist.

here is an example:

CHAPTER XII. Alice’s Evidence
‘Here!’ cried Alice, quite forgetting in the flurry of the moment how
great emphasis, looking hard at Alice as he said do.
CHAPTER VI. Pig and Pepper
CHAPTER VII. A Mad Tea-Party
CHAPTER VIII. The Queen’s Croquet-Ground
CHAPTER IX. The Mock Turtle’s Story

There is no other way that the word 'CHAPTER' appears in the text

  • 5
    Please edit your question and include an example of your file that we can use for testing. Will it always be "chapter"? Can it be "Chapter"? Or "CHAPTER"? How about "chapter 2"? What if "chapter" appears elsewhere in the file? Do we need it to be the first word on the line? The only word? We can't help you if you don't show us what we have to work with. Also, how would the directories be named? Do they exist? Do we need to create them? – terdon Mar 25 at 18:50
  • Please edit your question and include an example of your file that we can use for testing. – terdon Mar 25 at 21:31
  • do you know how can I upload a file? – emmy Mar 26 at 10:27
  • No, don't upload. Simply take a few example lines from your file (for instance, show us 3 chapters and 3-4 lines from each chapter) and just paste it into your question. Use the formatting tools to make it a quote. Then, show us how you would want this split. And please answer my other questions, what happens if we find "chapter" inside the text? Perhaps you have a sentence that reads "This opened a new chapter in her life". How can we know which "chapter" to cut at? – terdon Mar 26 at 11:03
  • thank you, I updated the post – emmy Mar 26 at 15:52

This solution assumes that:

  1. CHAPTER is always the first word of the line.
  2. It is always followed by one space, then a roman numeral (one or more of the capital letters I, V, X, L, C, D or M and ends with a ..

Then, we do it in two steps:

  1. Split each chapter into its own file, named CHAPTER_I.txt, CHAPTER_II.txt ... CHAPTER_N.txt (file is your input file):

    awk '/^CHAPTER [IVXLCDM]+/{name=$1"_"$2"txt"} {print > name}' file
  2. Move these files into their own directory:

    for file in CHAPTER_[IVXLCDM]*.txt; do 
        mkdir -p "${file//.txt}" && mv "$file" "${file//.txt}"
| improve this answer | |
  • Where is the part that you wrote because you assumed that CHAPTER comes in the begining of a line? – emmy Mar 26 at 21:42

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.