Mac环境下用split/awk按章节号分割韩文小说文本文件求助
Split Korean Novel by Chapter Numbers Using Awk (macOS)
Got it, since you’re on macOS and have awk available, this tool is perfect for your task—its pattern-matching capabilities let you dynamically create new files whenever a chapter header (starting with digits like 00001) is encountered. Here’s a robust, straightforward solution:
The Awk Command
Run this in your terminal, replacing input.txt with the path to your large novel file:
awk ' /^[0-9]+/ { # Close the previous chapter file to avoid hitting open file limits if (outfile) close(outfile) # Extract the leading chapter number (all digits at the start of the line) match($0, /^[0-9]+/) chap_num = substr($0, RSTART, RLENGTH) # Define the output filename (customize this as needed) outfile = "chapter_" chap_num ".txt" } # Write every line to the current chapter file { print > outfile }' input.txt
How It Works
Let’s break down the key parts so you understand what’s happening:
/^[0-9]+/: Matches any line that starts with one or more digits (your chapter numbers like 00001, 00002).if (outfile) close(outfile): Critical for large files—closes the previous chapter’s file before opening a new one to avoid exceeding macOS’s open file limit.match($0, /^[0-9]+/): Finds the position of the leading digits in the line.RSTARTgives the start index,RLENGTHgives the length of the matched digits.chap_num = substr(...): Pulls out the actual chapter number from the header line.outfile = "chapter_" chap_num ".txt": Creates a filename likechapter_00001.txtfor each chapter. You can tweak this (e.g., usechap_num ".txt"to get just00001.txt).{ print > outfile }: Writes every line to the current chapter file—this includes the header line and all content until the next chapter starts.
Customization Tips
- Adjust Filenames: If you want simpler or different naming (like
volume1_chap00001.txt), modify theoutfileline to fit your preference. - Test First: If you’re unsure, run the command on a small sample of your file first to verify the output matches what you expect.
- Handle Edge Cases: Even if your chapter headers have extra characters right after the digits (like
====================), the command still works because we only extract the leading numeric part.
Notes for macOS Users
- The
awkincluded with macOS is BSD awk, which supports all the functions used here—no need to install GNU awk unless you specifically want it. - Ensure you have write permissions in the directory where you run the command so the chapter files can be created.
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

