Parsing CSV-Like Text from the Command Line

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 110 of 205

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 to read, not to the rest of the loop.
  • -r keeps 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 csv module.

The examples were run with Bash 5.2.21, GNU coreutils 9.4, mawk 1.3.4 and Python 3.13.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Parsing CSV-Like Text from the Command Line and get answers drawn from it.

Signed-in readers only.