Processing CSV Files From the Command Line
A CSV file is a plain text table: one record per line, with values separated by commas. Because it is only text, the standard Unix tools can read it, and a few well chosen commands can answer questions that would otherwise mean opening a spreadsheet program. This is especially handy for large files, remote servers and quick checks.
The examples below use a small file called orders.csv with a header line and four columns.
id,customer,country,quantity
1,Alice,Canada,3
2,Bruno,Brazil,5
3,Chen,Canada,2
4,Dana,Norway,8
Look at the file first
Before processing anything, find out what you are dealing with.
head -n 5 orders.csv
wc -l orders.csv
The head command prints the first lines, which usually shows the header and a few sample records. The wc -l command counts lines, so subtract one for the header to get the record count. For a large file, less -S orders.csv lets you scroll sideways without wrapping long lines.
To line up the columns for easier reading, try column.
column -s, -t orders.csv
Pick columns with cut
The cut command extracts fields by number. Tell it the delimiter with -d and the columns with -f.
cut -d, -f2,4 orders.csv
This prints the second and fourth columns. It is quick and works well on simple files, but it has no idea about quoting, which is a limit we will return to below.
Filter rows with grep and awk
To keep only lines that contain a word, use grep.
grep ',Canada,' orders.csv
Matching the commas on both sides avoids false hits, such as a customer whose name happens to contain the same letters. For tests on a specific column, awk is more precise. It splits each line into fields and lets you write conditions.
awk -F, '$(3) == "Canada"' orders.csv
awk -F, 'NR == 1 || $(4) > 2' orders.csv
In awk, -F, sets the field separator, $(3) is the third column, and NR is the line number. The second command keeps the header line plus any row where the quantity is above two.
Sort and count
The sort command orders lines, and it can sort by a chosen column. To sort the data rows by quantity, largest first, while leaving the header on top:
(head -n 1 orders.csv; tail -n +2 orders.csv | sort -t, -k4,4nr)
Here -t, sets the separator, -k4,4 sorts on column four only, and n and r mean numeric and reverse. To count how many times each value appears in a column, combine cut, sort and uniq.
tail -n +2 orders.csv | cut -d, -f3 | sort | uniq -c | sort -nr
That pipeline skips the header, takes the country column, groups equal values together and counts them. The final sort -nr puts the most common value first. Remember that uniq only collapses neighbouring lines, so sorting first is required.
Summarise with awk
Awk can keep running totals, which makes it a small calculator for columns.
awk -F, 'NR > 1 { total += $(4); n++ } END { print "rows:", n, "total quantity:", total }' orders.csv
For a total per country, use an associative array.
awk -F, 'NR > 1 { sum[$(3)] += $(4) } END { for (c in sum) print c, sum[c] }' orders.csv
This is a group by, written in one line. Awk handles the loop, the array and the output with no extra files.
Know the limits of simple tools
Real CSV files can contain commas inside quoted values, such as "Smith, Jane", and even line breaks inside a quoted cell. Tools like cut and plain awk split on every comma and will break those rows apart. If you see columns shifting in your output, quoting is the likely cause.
Your options in that case:
- Use a tool built for CSV that understands quoting. Several open source command line utilities exist for this purpose.
- Write a short Python script with the standard
csvmodule, which handles quotes correctly. - Clean the file first, for example by exporting with a different delimiter such as tab or a pipe character, which rarely appears in data.
Other things to check before trusting results: the file encoding (UTF-8 is typical), Windows line endings that leave a stray carriage return at the end of the last column, and a byte order mark at the start of the file that can corrupt the first header name.
A safe workflow
Never modify the original file in place. Send results to a new file with >, and keep the source untouched. Test each stage of a pipeline by running it alone, then add the next stage. When a pipeline grows past three or four steps, move it into a script with a clear name and a comment on why it exists.
Frequently Asked Questions
How do I skip the header line?
Use tail -n +2 file.csv to print everything from the second line onward, or in awk add a condition such as NR > 1. To keep the header while processing the rest, print it separately first.
Can I use a different delimiter, such as a semicolon or tab?
Yes. Set -d for cut, -t for sort, and -F for awk to the delimiter you need. For tabs, you can write $'\t' in Bash to represent the tab character.
When should I stop using the command line and use a script?
Switch when quoting, dates or multi line values cause trouble, or when the pipeline becomes hard to read. A short Python script is easier to test and extend than a long chain of cut and awk commands.