csplit

Context-aware file splitting based on patterns or line numbers.

Category: Text Processing Pattern Split Logs coreutils

What it does

csplit splits a file into sections based on context (patterns or line numbers), rather than fixed byte size like split. It is ideal when dividing logs, configuration blocks, or structured documents.

How it works (mechanical)

csplit reads an input file sequentially and creates numbered output files (xx00, xx01, etc.) whenever a match expression or line offset is encountered.

10 Practical Examples

# 1) Split at line 100
csplit file.txt 100
# 2) Split at multiple line numbers
csplit file.txt 100 200 300
# 3) Split on regex match
csplit file.txt '/^SECTION/'
# 4) Split on every occurrence of a pattern
csplit file.txt '/^User:/' '{*}'
# 5) Suppress size output
csplit -s file.txt 100
# 6) Custom filename prefix
csplit -f part_ file.txt 100
# 7) Split Apache log per day marker
csplit access.log '/^===/' '{*}'
# 8) Split config blocks
csplit config.conf '/^\[/' '{*}'
# 9) Keep empty sections
csplit -z file.txt '/PATTERN/' '{*}'
# 10) Combine with nl for debugging
nl file.txt | csplit - '/^ *200/'

Notes & Gotchas

Historical Context

csplit is part of GNU coreutils and was designed for structured text workflows, where splitting based on meaning (sections, markers, blocks) matters more than size.

Related Commands