linux - how i can split a text file in parts (5 lines each)?
- User
linux - how i can split a text file in parts (5 lines each)?
- Assistant
Here are three easy ways to chop a large text file into chunks of 5 lines each on Linux.
1. Using
splitThe simplest tool for the job is GNU split:
split -l 5 yourfile.txt chunk_•
-l 5tells it “five lines per file.”
•chunk_is the prefix for output files; by default you’ll get files named
chunk_aa, chunk_ab, chunk_ac, …Customizing
- Change suffix length (e.g. three letters):
split -l 5 -a 3 yourfile.txt part_→part_aaa, part_aab, … - Use numeric suffixes instead of letters:
split -l 5 --numeric-suffixes=1 yourfile.txt part_→part_01, part_02, … - Add a file extension:
split -l 5 yourfile.txt part_ --additional-suffix=".txt"
2. Using
csplitIf you want more complex patterns or to keep the last incomplete chunk, try
csplit:csplit -z -f part_ yourfile.txt 5 "{*}"•
-zremoves zero‐length output files.
•-f part_sets the filename prefix.
•5 "{*}"means “every 5 lines, repeat until end.”
Output:part_00, part_01, part_02, …
3. Using
awkFor ultimate control you can script it in
awk:awk '{ file = sprintf("slice_%03d.txt", int((NR-1)/5)+1) print >> file }' yourfile.txtWhat’s happening here?
NRis the current line-number.int((NR-1)/5)+1groups lines 1–5 → slice_001.txt, 6–10 → slice_002.txt, etc.print >> fileappends the current line to the right output file.
Pick whichever method feels easiest. If you need to preserve a header line in every chunk, let me know and I can show you a tweak!
- Change suffix length (e.g. three letters):
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.