I have a txt file which contains chapters, I want to copy each chapter to a new txt file using bash. for example:
"CHAPTER I. Down the Rabbit-Hole Alice was beginning to get very.......
CHAPTER II. The Pool of Tears
'Curiouser and curiouser,' cried Alice (she was so much surprised; that for the moment she quite forgot how to speak good English). ..... "
I want to create 2 files 1 for each chapter.
awk 'BEGIN{start="0"; end="0"; chapters="0"}
{if($1 -eq chapter){
chapter++
sed -n "$start,$end" Alice_book_aux > Alice_book_chapter_$chapter
start = end
}
end++;}' Alice_book
This is what I thought I should do but is won't work:(
I'll make assumptions based on the given example.
AWK
has an input parser that can process input through regexp filters SED
is an adequate tools to take excerpts from input, but AWK
will suffice here. Thus your revised code:
awk 'BEGIN {chapter=0;chapfile="";}
/^"?CHAPTER / {
chapter++;
chapfile="Alice_book_chapter_"chapter;
printf "" > chapfile;
}
{ if (chapter -gt 0) {
print >> chapfile;
}
}' Alice_book
As suggested by @karakfa, the awk script can be reduced to this:
awk '/^"?CHAPTER / {
chapter++;
chapfile="Alice_book_chapter_"chapter;
}
chapter{
print > chapfile;
}
' Alice_book
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.