Site icon New Generation Enterprise Linux

Stop parsing CSV files with regex like a sucker

Text Processing (Grep/Sed/Awk)

Stop parsing CSV files with regex like a sucker

🧩 The Challenge

Dealing with CSV files that have quoted fields containing commas is a special kind of hell. I spent way too long trying to write a custom sed script for this before realizing I was just setting myself up for data corruption.

💡 The Fix

Use awk with a field separator that actually understands the CSV structure by ignoring commas inside quotes. It saves you from the inevitable headache of trying to split on a comma that shouldn’t be a delimiter.

awk -v FPAT='[^,]*|"[^"]*"' '{print $1, $3}' input.csv

⚙️ Why It Works

Setting FPAT tells awk to treat anything inside quotes as a single field rather than breaking it apart at every single comma it encounters. It makes messy exports actually readable without needing to install a heavyweight library.

🚀 Pro-Tip: If your CSV uses escaped quotes like “” inside the string, just strip those out with a quick gsub before you process the lines.

Linux Tips & Tricks | © ngelinux.com | 12/6/2026

0 0 votes
Article Rating
Exit mobile version