brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: csplit cuts a text file into pieces wherever a pattern matches

Linux
~/tips/tip-linux-csplit-split-on-pattern

csplit -s -z -f part- dump.sql '/^CREATE TABLE/' '{*}'

Split a long log or dump into separate files at every line that starts a new section.

split cuts a file into chunks of a fixed size. When the file has natural sections, like one block per day or one table per dump, csplit cuts it at the start of each section instead.

csplit -s -z -f part- dump.sql '/^CREATE TABLE/' '{*}'

The pattern between slashes marks where a new piece starts. '{*}' repeats that pattern as often as it matches, so you get one file per table, named part-00, part-01 and so on. -f sets that prefix. -s keeps it quiet; without it, csplit prints the size of every piece. -z removes empty pieces, which you would otherwise get when the file starts right on a match.

The line that matches becomes the first line of the new piece, so every file starts with its own header. I find that a lot easier to read than one giant file in an editor.

A line number works as well as a pattern. csplit big.txt 1000 cuts after line 999 and gives you two parts.

The first piece holds everything before the first match, which is often a short header block, so check part-00 before you throw it away. If you give a fixed repeat count like '{5}' and the pattern runs out earlier, csplit stops with an error and deletes the pieces it made, unless you add -k to keep them.

Further reading: GNU coreutils: csplit invocation

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link