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
To split a text file into parts of 5 lines each in Linux, you can use one of these methods:
1. Using
split(Simplest Method)split -l 5 input.txt output_prefix_-l 5: Split every 5 lines.input.txt: Your source file.output_prefix_: Prefix for output files (e.g.,output_prefix_aa,output_prefix_ab).- To add numeric suffixes (e.g.,
part_001.txt,part_002.txt):split -l 5 input.txt -d -a 3 --additional-suffix=.txt part_-d: Use numeric suffixes (instead ofaa,ab).-a 3: Use 3-digit suffixes (e.g.,001).--additional-suffix=.txt: Append.txtto filenames.
2. Using
awk(Flexible Formatting)awk 'NR%5==1 {file="part_" sprintf("%03d", (NR-1)/5+1) ".txt"} {print > file}' input.txt- Creates files like
part_001.txt,part_002.txt, etc. - Automatically handles uneven line counts in the last file.
3. Using
csplit(For Contextual Splits)csplit -s -z input.txt /^/ {*} -f part_ -b '%03d.txt' 5- Splits every 5 lines.
-f part_: Prefixpart_.-b '%03d.txt': 3-digit numeric suffixes with.txt.- Requires GNU
csplit(standard on most Linux distros).
Example Output
For a file with 12 lines, you’ll get:
output_prefix_aa # Lines 1-5 output_prefix_ab # Lines 6-10 output_prefix_ac # Lines 11-12 (last part)
Notes:
- Uneven Files: The last file will contain the remaining lines (≤5 lines).
- Install Missing Tools: If
split/csplitoptions aren’t supported (e.g., on macOS), install GNU coreutils:
Then usebrew install coreutils # macOSgsplit(GNU version ofsplit).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.