Yes, you can split a CSV file with bash using commands like split, head, tail, awk, or csplit. The simplest way is split -l 1000 input.csv part_, which creates files of 1000 lines each, but you must handle the header row separately so it appears in every output file.
Why Split a CSV in Bash at All
CSV files grow fast. A few million rows from a database export, a server log, or a marketing list can reach hundreds of megabytes. Many tools choke on files that large: Excel has a hard limit of 1,048,576 rows per sheet, text editors lag, and some command-line utilities run out of memory. Splitting the file into smaller chunks lets you process each piece individually, upload them with size limits, or parallelize jobs with xargs. Bash is already on every Linux and macOS system, and on Windows you can use Git Bash or WSL, so no extra software is needed.
The Basic split Command and Its Pitfalls
The core tool is split. Its most useful flags for CSV work are:
-l N– put N lines per output file (default is 1000).-d– use numeric suffixes (00, 01, 02) instead of letters (aa, ab, ac).-a N– set suffix length (e.g.,-a 3gives 000, 001).--additional-suffix=.csv– add an extension to each output file.
Example: split -l 5000 -d --additional-suffix=.csv sales.csv chunk_ creates chunk_00.csv, chunk_01.csv, etc., each with 5000 lines. The problem: the first line of sales.csv is the header, so chunk_00.csv contains the header plus 4999 data rows, while every other chunk has no header. If you need the header in every file (common for re-importing), you must strip it first and re-add it after splitting.
How to Keep the Header in Every Split File
The cleanest approach uses tail to skip the header, then split, then a loop to prepend the header. Assuming your header is the first line:
- Extract the header:
head -n 1 input.csv > header.txt - Split the rest:
tail -n +2 input.csv | split -l 1000 -d --additional-suffix=.csv - chunk_ - Loop over the new files and prepend the header:
for f in chunk_*.csv; do cat header.txt "$f" > tmp && mv tmp "$f"; done
The - in the split command tells it to read from standard input. The loop uses cat to combine the header and the chunk into a temporary file, then moves it back. This works fine on files with quoted commas or newlines inside fields, because split counts physical lines, not logical CSV records. That is a critical limitation: if any field contains a newline character (which is legal in CSV when enclosed in double quotes), a simple line-based split will break that record across two files.
Handling Quoted Newlines: When Line Counts Fail
CSV files can contain multiline fields. For example, a description column might have a value like "Line1. That is one logical record but two physical lines. Using
Line2"split -l will cut between those two lines, producing invalid CSV. If your data is well-formed and you know it has no embedded newlines, line splitting is fine. If you are not sure, use a tool that understands CSV structure. awk can track whether you are inside quotes:
awk 'BEGIN {chunk=0; lines=0; out="chunk_00.csv"}
{ if (NR==1) {header=$0; next}
inq=0; for(i=1;i<=length($0);i++){c=substr($0,i,1); if(c=="\"") inq=!inq}
if (lines==0) print header > out;
print > out; lines++;
if (inq==0 && lines>=1000) {close(out); chunk++; lines=0; out=sprintf("chunk_%02d.csv", chunk)}
}' input.csv
This script counts quotes per line to decide if a record is complete. It is not perfect (escaped quotes inside fields break it), but it handles the common case. For truly robust splitting, consider a dedicated CSV tool like csvkit or a Python script, but that moves beyond pure bash.
Choosing the Right Split Size and Suffix Format
Decide chunk size based on your downstream tool. If you are importing into Excel, keep each file under 1,048,576 rows. If you are uploading to a service with a 10 MB limit, calculate rows by file size: wc -l input.csv gives line count, du -h input.csv gives size, then divide. For large files, use -a 3 or more to avoid running out of suffix space (default two characters only gives 100 files for numeric suffixes, 676 for letters). Example: split -l 100000 -d -a 3 --additional-suffix=.csv big.csv part_ yields part_000.csv through part_999.csv. Use --numeric-suffixes=1 if you want numbering to start at 1 instead of 0.
Common Problems and How to Fix Them
- Missing header in later files – solved by the header-prepend loop above.
- Files with no extension – add
--additional-suffix=.csv. - Windows line endings (CRLF) –
splittreatsas part of the line. Use
sed 's/\r$//' input.csv | split ...to strip them first, or convert withdos2unix. - Empty lines at the end – they create empty chunks. Filter them out with
grep -v '^$'before splitting. - File naming conflicts – if you run split twice, it overwrites existing chunks. Use a unique prefix or delete old files first:
rm -f chunk_*.csv. - Very large files (multiple GB) –
splitis efficient because it streams, but the header-prepend loop reads each chunk twice. For huge files, useawkto write headers directly as shown above.
Alternatives and When to Use Them
Bash split is fast and simple, but it has limits. If your CSV has complex quoting, use csvkit‘s csvsplit command (e.g., csvsplit -n 1000 input.csv) which respects quoted fields. Python with the csv module is more flexible for custom logic. For splitting by number of rows with a header, awk is a good middle ground. On Windows without bash, PowerShell’s Get-Content | Select-Object -First works but is much slower. For most everyday tasks, the simple split command with a header loop is all you need.
Frequently Asked Questions
How do I split a CSV by number of rows, not lines?
If your CSV has no quoted newlines, rows equal lines, so split -l works. If it does have embedded newlines, you need a CSV-aware tool. The awk script above tracks quotes and only splits when a record is complete. For a one-off, you can also use Python: python3 -c "import csv,sys; ..." but that is not pure bash.
Can I split a CSV file without losing the header?
Yes. The standard method is to extract the header with head -n 1, split the rest with tail -n +2 | split, then loop to prepend the header to each chunk. That is the most common solution and works reliably for files without multiline fields.
What is the difference between split and csplit?
split divides a file into equal-sized pieces by lines or bytes. csplit splits based on context – for example, you can split every time a line matches a pattern like /^ID,/. For CSV, split is usually what you want because you care about row counts, not content patterns.
How do I split a CSV by file size instead of line count?
Use split -b 10M input.csv part_ to create 10-megabyte chunks. But be careful: this can cut a line in half. To avoid that, use split -C 10M (or --line-bytes), which splits at line boundaries while staying under the size limit. The header issue still applies.
Does split work on macOS and Windows?
Yes. macOS has split built in. Windows does not natively, but you can use Git Bash, WSL, or Cygwin. The syntax is identical across these environments. On macOS, the default split is the BSD version, which supports -d and --additional-suffix in recent versions; if not, use -a and rename files with a loop.
Is there a risk of corrupting the CSV when splitting?
Only if the file contains quoted newlines or if you split mid-line with -b. For plain line-based CSV, splitting is safe. Always verify by checking that the number of lines in all chunks plus the header equals the original line count: wc -l chunk_*.csv | tail -1.
Related
- Java Code to Split String: Methods & Examples
- Enum in SQL Server: How to Use It & Why It Doesn’t Exist
- Generate Random Number in Excel: RAND, RANDBETWEEN & More
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Check for Duplicates in Excel Step by Step GuideTo check for duplicate values in Excel, select the cells you want to inspect, then choose Home >…
- Import a Color Palette in Excel: Step-by-Step GuideTo import a color palette in Excel for Microsoft 365 on Windows, load an Office theme file (.thmx)…
- Freeze Panes in Excel: Keep Rows and Columns VisibleTo keep headings or labels visible while you scroll in Excel, use View > Freeze Panes. Choose Freeze…
- How to Archive Emails in Outlook Desktop: Step-by-StepTo archive an email in Outlook desktop, select it and choose Home > Archive. Outlook removes the message…
- Entry Level Data Entry: Real Jobs, Pay, SkillsEntry level data entry means jobs where you input, update, and verify information in computer systems, databases, or…
- Stampin’ Up Inventory Spreadsheet: What to TrackA Stampin’ Up! inventory spreadsheet is a practical way to track the paper, stamps, ink, tools, and other…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.