csplit — Split by pattern
Linux / Basic Linux commands / csplit.html
Splits a file at points defined by patterns or line numbers.
Basic Information
| Command Name | csplit |
|---|---|
| One-line Introduction | Splits a file at points defined by patterns or line numbers. |
| Provided by | GNU coreutils |
| Official Documentation | https://man7.org/linux/man-pages/man1/csplit.1.html |
| Supported Operating Systems | Linux, macOS, BSD |
| Installation Status | Installed by default |
| Category | Linux basic commands (tags: Linux basic commands (tags: csplit, split, regex, section)) |
What is this command?
Unlike split, csplit cuts a file at points where a regex or line number occurs. It is useful for separating log sessions at each start marker.
Patterns use /regex/ syntax, with {n} for repetition and {*} to repeat to the end. If a pattern never matches, the section is not created, so test against real data first.
What problems does it solve?
- Separating logs at each session marker
- Splitting a file containing several documents
- Cutting sections at known line numbers
- When split cannot respect content boundaries
Key features
Pattern split
A new file starts at each /regex/ match.
- When to use: Splitting on a recurring delimiter
- What you get: Content boundaries are respected.
- Limitations: No match means no file is produced.
Repetition
{n} and {*} control how often to split.
- When to use: When the number of sections is known
- What you get: Prevents unwanted extra pieces.
- Limitations: A wrong count merges the final sections.
Output names
Prefix and format control the output names.
- When to use: When later steps rely on naming
- What you get: Script integration becomes easier.
- Limitations: Existing files can be overwritten.
Installation and usage
Check whether it is installed
csplit --version
sudo apt install coreutils # Debian/Ubuntu sudo dnf install coreutils # Fedora
Real-world examples
Split by session
Start a new file at each START line.
csplit app.log '/^START/' '{*}'
Split at a line
Split before line 100.
csplit notes.txt 100
Limit sections
Split only twice.
csplit app.log '/^START/' '{2}'