Parsing CSV-Like Text from the Command Line
CSV (comma-separated values) is one of the most common formats for exchanging tabular data: exports from spreadsheets and databases, reports from web services, inventory lists, logs. Each line is a record, and commas separate the fields. Because the format is plain text, Bash tools such as cut, sort, awk and read can process it directly.
The phrase "CSV-like" matters. Simple CSV, where no field contains a comma, a quote or a line break, splits cleanly at every comma, and the shell tools handle it well. Full CSV allows quoted fields that contain commas, quotes and even newlines, and splitting at every comma then gives wrong results. This lesson shows how to process simple CSV safely, how to recognize when data is not simple, and what to use instead.
The Sample File
The examples use orders.csv:
order_id,customer,city,amount,status
1001,Ana,Lisbon,120.50,paid
1002,Bo,Oslo,75.00,pending
1003,Cy,Lisbon,310.25,paid
1004,Dee,Porto,,cancelled
1005,Eve,Oslo,42.10,paid
The first line is a header that names the columns. Order 1004 has an empty amount field, shown by two commas in a row.
Extracting Columns with cut
For simple CSV, cut with a comma delimiter selects columns by number:
cut -d, -f2,4 orders.csv
customer,amount
Ana,120.50
Bo,75.00
Cy,310.25
Dee,
Eve,42.10
An empty field stays empty, and the output keeps commas between the selected columns, so the result is still CSV. cut cannot reorder columns or test values; for that, use awk.
Processing Columns with awk
awk -F, splits each line at commas. Combined with NR > 1 to skip the header, it can filter, compute and reformat:
awk -F, 'NR > 1 && $5 == "paid" { print $1, $2, $4 }' orders.csv
1001 Ana 120.50
1003 Cy 310.25
1005 Eve 42.10
Totals use an END block:
awk -F, 'NR > 1 && $5 == "paid" { total += $4 } END { printf "paid total: %.2f\n", total }' orders.csv
paid total: 472.85
Grouping by a column with an associative array gives a summary per city. The condition $4 != "" leaves out the order with no amount, so it does not count toward the number of orders:
awk -F, 'NR > 1 && $4 != "" { sum[$3] += $4; n[$3]++ }
END { for (c in sum) printf "%s,%d,%.2f\n", c, n[c], sum[c] }' orders.csv | sort
Lisbon,2,430.75
Oslo,2,117.10
The output is itself CSV (city, number of orders, total), so it can be saved to a file or opened in a spreadsheet.
Writing CSV Output
To keep commas between the printed fields, set the output field separator OFS to a comma:
awk -F, -v OFS=, '{ print $1, $2, $5 }' orders.csv | head -3
order_id,customer,status
1001,Ana,paid
1002,Bo,pending
Adding a computed column keeps the header consistent by handling line 1 separately:
awk -F, -v OFS=, '
NR == 1 { print $0, "vat"; next }
{ vat = ($4 == "" ? "" : sprintf("%.2f", $4 * 0.23)); print $0, vat }
' orders.csv
order_id,customer,city,amount,status,vat
1001,Ana,Lisbon,120.50,paid,27.71
1002,Bo,Oslo,75.00,pending,17.25
1003,Cy,Lisbon,310.25,paid,71.36
1004,Dee,Porto,,cancelled,
1005,Eve,Oslo,42.10,paid,9.68
cond ? a : b is awk's conditional expression, and sprintf formats a number into a string without printing it. The empty amount produces an empty VAT field instead of a misleading 0.00.
Converting CSV to TSV
The $1 = $1 idiom (lesson 109) rebuilds each line with the new output separator. Here it turns commas into tabs:
awk -F, -v OFS='\t' '{ $1 = $1; print }' orders.csv | head -2
order_id customer city amount status
1001 Ana Lisbon 120.50 paid
Tab-separated values are often safer than CSV for shell processing, because tabs rarely appear inside data.
Selecting a Column by Its Header Name
Column numbers break when someone adds or reorders columns in the source file. Looking up the column by its header name makes a script more robust:
awk -F, -v col=city '
NR == 1 {
for (i = 1; i <= NF; i++) if ($i == col) c = i
if (!c) { print "no column " col > "/dev/stderr"; exit 1 }
next
}
{ print $c }
' orders.csv
Lisbon
Oslo
Lisbon
Porto
Oslo
On the header line, the loop compares each field with the requested name and remembers its position in c. If no column matches, the program prints an error to standard error and exits with status 1:
no column zip
For data lines, $c selects the field at the remembered position. The variable c can be used after $, just like $NF.
Sorting CSV Data
sort -t, sets the comma as the field delimiter, and -k chooses the key (lesson 107). tail -n +2 prints everything from line 2 on, which removes the header so it is not sorted with the data:
tail -n +2 orders.csv | sort -t, -k4,4nr | head -3
1003,Cy,Lisbon,310.25,paid
1001,Ana,Lisbon,120.50,paid
1002,Bo,Oslo,75.00,pending
To keep the header on top of the sorted data, print it separately inside a command group:
{ head -n 1 orders.csv; tail -n +2 orders.csv | sort -t, -k2,2r; }
order_id,customer,city,amount,status
1005,Eve,Oslo,42.10,paid
1004,Dee,Porto,,cancelled
1003,Cy,Lisbon,310.25,paid
1002,Bo,Oslo,75.00,pending
1001,Ana,Lisbon,120.50,paid
Counting the values of one column uses the familiar pipeline:
tail -n +2 orders.csv | cut -d, -f5 | sort | uniq -c | sort -rn
3 paid
1 pending
1 cancelled
Reading CSV Lines in a Bash Loop
When each record needs shell commands, such as creating a directory or calling another program, a while read loop splits each line into variables. Setting IFS=, for the read command makes the comma the separator:
while IFS=, read -r id customer city amount status; do
printf '%s from %s: %s\n' "$customer" "$city" "${amount:-n/a}"
done < <(tail -n +2 orders.csv)
Ana from Lisbon: 120.50
Bo from Oslo: 75.00
Cy from Lisbon: 310.25
Dee from Porto: n/a
Eve from Oslo: 42.10
How it works:
IFS=,applies only toread, not to the rest of the loop.-rkeeps backslashes as literal characters.- Each field goes into the next variable name in order. An empty field gives an empty variable, which
${amount:-n/a}replaces with a default (lesson 45). < <(tail -n +2 orders.csv)feeds the data through process substitution (lesson 151), which skips the header and, unlike a pipe, keeps the loop in the current shell so variables set inside it survive.
Another way to skip the header is to read it first with a separate read, inside a group that shares the same input. The variable name _ is a common convention for fields that are not needed:
{
read -r header
while IFS=, read -r id customer _ amount _; do
echo "$id $customer $amount"
done
} < orders.csv
The first two lines of output are:
1001 Ana 120.50
1002 Bo 75.00
Extra Fields Go into the Last Variable
If a line has more fields than variable names, the last variable receives the rest of the line, commas included:
echo 'a,b,c,d' | { IFS=, read -r x y; echo "x=$x y=$y"; }
x=a y=b,c,d
This is useful for a final free-text column, but it also means a line with an unexpected extra comma silently shifts data into the last variable.
Reading Fields into an Array
read -a stores all fields in an indexed array (lesson 97), which suits files with many columns:
IFS=, read -r -a f <<< '1001,Ana,Lisbon,120.50,paid'
echo "${#f[@]} ${f[2]}"
5 Lisbon
Array indexes start at 0, so ${f[2]} is the third field.
A Last Line Without a Newline
read returns a failure status when it reaches the end of input without a newline, so a loop skips a final line that lacks one. nonl.csv was created with printf 'id,name\n1,Ana\n2,Bo':
while IFS=, read -r id name; do echo "$id:$name"; done < nonl.csv
id:name
1:Ana
The record for Bo was lost. Adding || [[ -n $id ]] processes a final partial line too:
while IFS=, read -r id name || [[ -n $id ]]; do echo "$id:$name"; done < nonl.csv
id:name
1:Ana
2:Bo
Lesson 114 covers reading files line by line in more depth.
Windows Line Endings
CSV files exported on Windows usually end each line with a carriage return and a line feed (CRLF). The tools split at the line feed, so the carriage return stays at the end of the last field. It is invisible in most terminals but breaks comparisons. cat -A shows it as ^M:
printf 'id,name,city\r\n1,Ana,Lisbon\r\n2,Bo,Oslo\r\n' > crlf.csv
awk -F, '{ print $3 "|" }' crlf.csv | cat -A
city^M|$
Lisbon^M|$
Oslo^M|$
A comparison such as [[ $city == Oslo ]] fails, because the value is really Oslo followed by a carriage return. Three common fixes:
tr -d '\r' < crlf.csv | cut -d, -f3 # remove every carriage return first
awk -F, '{ sub(/\r$/, ""); print $3 }' crlf.csv # remove it inside awk
city=${city%$'\r'} # remove it from a shell variable
The first two print city, Lisbon and Oslo with no trailing characters. In a read loop, the third form strips the carriage return from the last variable before it is compared:
while IFS=, read -r id name city; do
city=${city%$'\r'}
[[ $city == Oslo ]] && echo match
done < crlf.csv
match
Without the city=${city%$'\r'} line, the same loop prints nothing. $'\r' is Bash's notation for a carriage return, and ${var%pattern} removes it from the end of the value (lesson 54).
Trimming Spaces Around Fields
Some files put spaces after commas. A plain comma separator keeps them as part of the value. A regular expression separator that includes optional spaces removes them:
printf 'a, b ,c\n' | awk -F, '{ print "[" $2 "]" }'
printf 'a, b ,c\n' | awk -F' *, *' '{ print "[" $2 "]" }'
[ b ]
[b]
Joining Two CSV Files
awk can read a lookup file first and use it while processing a second file. NR == FNR is true only while the first file is being read, because FNR restarts at 1 for each file while NR keeps counting (lesson 109). cities.csv maps cities to country codes:
city,country
Lisbon,PT
Oslo,NO
Porto,PT
awk -F, -v OFS=, '
FNR == 1 { next }
NR == FNR { country[$1] = $2; next }
{ print $1, $2, $3, country[$3] }
' cities.csv orders.csv
1001,Ana,Lisbon,PT
1002,Bo,Oslo,NO
1003,Cy,Lisbon,PT
1004,Dee,Porto,PT
1005,Eve,Oslo,NO
The first rule skips the header of each file. The second stores each city's country while reading cities.csv. The third runs only for orders.csv and adds the matching country.
When CSV Is Not Simple: Quoted Fields
Full CSV, as defined in RFC 4180 and produced by spreadsheets, wraps a field in double quotes when it contains a comma, a double quote or a line break, and writes a literal double quote as two double quotes. quoted.csv uses these rules:
id,name,city,note
1,"Silva, Ana",Lisbon,ok
2,Bo,"New York, NY","said ""hi"""
3,Cy,Porto,
Splitting at every comma gives the wrong number of fields:
awk -F, '{ print NF ": " $2 }' quoted.csv
4: name
5: "Silva
5: Bo
4: Cy
Line 2 now has five fields and its name is "Silva, with the rest of the name pushed into the next column. cut -d,, sort -t, and IFS=, read all fail the same way. Checking the field count is a quick way to detect this problem:
awk -F, '{ print NF }' orders.csv | sort -u
5
A single value means every line of orders.csv has the same number of fields. Several values point to quoted commas or broken lines.
Using a Real CSV Parser
For files that may contain quoted fields, use a tool that implements the CSV rules. Python is installed on most Linux systems, and its standard csv module can be used directly from a Bash script:
python3 -c 'import csv, sys
for row in csv.reader(sys.stdin):
print(len(row), "|".join(row))' < quoted.csv
4 id|name|city|note
4 1|Silva, Ana|Lisbon|ok
4 2|Bo|New York, NY|said "hi"
4 3|Cy|Porto|
Every row now has four fields, the commas inside quotes are kept, and "" became a single ". csv.DictReader uses the header line to give each column a name:
python3 -c 'import csv, sys
for row in csv.DictReader(sys.stdin):
print(row["name"], "->", row["city"])' < quoted.csv
Silva, Ana -> Lisbon
Bo -> New York, NY
Cy -> Porto
Dedicated command-line tools exist as well, such as csvkit, mlr (Miller) and xsv, and GNU awk offers the FPAT variable and, in recent versions, a --csv option. These are separate installs or GNU-specific features and were not used for this lesson.
Choosing an Approach
- Simple CSV, quick column extraction:
cut -d,. - Simple CSV, filtering, totals, grouping, reformatting:
awk -F,. - Simple CSV, shell commands per record:
while IFS=, read -r ...with process substitution or a redirected file. - Files from Windows: remove carriage returns first.
- Any file that may contain quoted fields: a real CSV parser, such as Python's
csvmodule.
The examples were run with Bash 5.2.21, GNU coreutils 9.4, mawk 1.3.4 and Python 3.13.