For command line data processing, CSV is almost always the right choice because it is plain text, universally supported by standard Unix tools, and easy to script. XLSX is a binary, compressed format that requires special libraries and is slower to work with. However, there are specific cases where XLSX is necessary, such as when you need to preserve formulas, multiple sheets, or formatting. This guide will walk you through the decision process and show you how to handle both formats from the command line.
What You'll Need
- A Unix-like environment (Linux, macOS, or Windows Subsystem for Linux) with standard tools like
grep,awk,sed, andsort. - Python 3 with the
pandaslibrary installed (for reading and writing XLSX files). Install withpip install pandas openpyxl. - Optionally,
csvkitfor advanced CSV operations (pip install csvkit). - Basic familiarity with the command line and shell scripting.
Step-by-Step
- Identify your primary use case. Ask yourself: Do you need to process data with standard tools like
grep,awk, orsort? Do you need to combine multiple files easily? Do you need to preserve formulas, multiple sheets, or cell formatting? If the answer to the first two is yes and the last is no, choose CSV. If you need multiple sheets or formulas, you may need XLSX, but you will have to convert to CSV for most command line operations. - Check the source of your data. If you are exporting data from a database or an API, CSV is often the native export format. If you are receiving data from a colleague or a client, it may come as XLSX. In that case, you will need to convert it to CSV before processing.
- Convert XLSX to CSV. When you have an XLSX file, use Python with pandas to convert it to CSV. Create a script like this:
Save asimport pandas as pd import sys input_file = sys.argv[1] output_file = sys.argv[2]Read the first sheet by default; specify sheet_name='Sheet2' for others
df = pd.read_excel(input_file, sheet_name=0) df.to_csv(output_file, index=False)convert_xlsx_to_csv.pyand runpython convert_xlsx_to_csv.py data.xlsx data.csv. This will extract the first sheet. If you need a specific sheet, changesheet_name=0to the sheet name or index. - Handle multiple sheets. If your XLSX has multiple sheets, you can either convert each sheet separately or combine them. To list sheet names, use
python -c "import pandas as pd; print(pd.ExcelFile('data.xlsx').sheet_names)". Then convert each sheet by modifying the script to loop over all sheets, or use thesheet_name=Noneoption to get a dictionary of DataFrames. - Process the CSV with standard tools. Once you have a CSV, you can use standard commands. For example, to filter rows where the second column equals "active", use
awk -F',' '$2 == "active"' data.csv. To sort by the first column, usesort -t',' -k1,1 data.csv. To count unique values in the third column, usecut -d',' -f3 data.csv | sort | uniq -c. - Handle CSV quirks. CSV files can have quoted fields with commas, newlines, or escaped quotes. For robust parsing, use a proper CSV library. In Python, use
csvmodule or pandas. For command line, usecsvkit'scsvgrepandcsvgrepcommands. For example,csvgrep -c 2 -m active data.csvfilters rows where column 2 matches "active". - Convert CSV back to XLSX if needed. If your final output must be XLSX (for example, to send to a non-technical colleague), convert back using pandas. A simple script:
Runimport pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.to_excel(sys.argv[2], index=False)python convert_csv_to_xlsx.py data.csv data.xlsx. - Consider using a data processing tool. For more complex transformations, consider using
jqfor JSON, but for tabular data,csvkitprovidescsvgrep,csvgrep,csvjoin, andcsvstat. These are more reliable than rawawkfor messy CSV data. - Automate the workflow. Write a shell script that converts XLSX to CSV, processes it, and converts back if needed. For example:
#!/bin/bash python convert_xlsx_to_csv.py "$1" temp.csvProcess temp.csv with standard tools
sort -t',' -k1,1 temp.csv -o sorted.csv python convert_csv_to_xlsx.py sorted.csv "${1%.xlsx}_processed.xlsx" rm temp.csv sorted.csv - Test with a small sample. Before running on a large file, test your pipeline on a small sample to ensure the data is parsed correctly. Use
head -n 100 data.csvto inspect the first few rows.
Common Mistakes
- Using XLSX directly with Unix tools. Tools like
greporawkcannot read XLSX because it is a binary format. You will get binary garbage or errors. Always convert to CSV first. - Ignoring CSV quoting. If a field contains a comma, it is quoted in CSV. A naive
cut -d','will split it incorrectly. Always use a proper CSV parser. - Assuming all XLSX files have the same structure. Sheet names, column order, and data types vary. Always inspect the file before processing.
- Forgetting about encoding. CSV files may be in UTF-8, but sometimes they are in Latin-1 or other encodings. Use
file data.csvto check, and convert withiconvif needed. - Overwriting the original file. When converting, use a different output filename to avoid accidental data loss.
Tips
- Use
csvkitfor complex CSV operations. It handles quoting, encoding, and provides SQL-like queries. For example,csvgrep -c 1 -r '^[0-9]+$' data.csvfilters rows where column 1 is all digits. - Keep a backup of the original XLSX. If you convert to CSV, you lose formulas, formatting, and multiple sheets. Keep the original for reference.
- Use
headandtailto inspect large files. Before running a heavy operation, check the first few rows to verify the format. - Consider using
pandasfor complex transformations. If you need to join, pivot, or aggregate data, pandas is more powerful than shell tools. - Use
in2csvfrom csvkit. It can convert XLSX to CSV with one command:in2csv data.xlsx > data.csv. It also supports other formats like JSON.
Troubleshooting
If your conversion or processing fails, follow these steps:
- Check the file path and permissions. Ensure the file exists and is readable. Use
ls -lto check. - Verify the XLSX is not corrupted. Try opening it in a spreadsheet application. If it won't open, the file may be damaged.
- Check for password protection. If the XLSX is password-protected, pandas will fail. You will need to remove the password first.
- Inspect the CSV output. After conversion, run
head -n 5 data.csvto see if the data looks correct. Look for missing columns or garbled text. - Handle encoding issues. If you see mojibake, use
iconv -f ISO-8859-1 -t UTF-8 data.csv > data_utf8.csv(adjust the source encoding). - If pandas fails with "No module named 'openpyxl'", install it with
pip install openpyxl.
Frequently Asked Questions
Can I use grep directly on an XLSX file?
No, grep treats the file as binary and will output binary data or errors. You must convert to CSV first.
What if I need to process multiple sheets from an XLSX?
Convert each sheet to a separate CSV using pandas with sheet_name parameter, or combine them into one CSV with a column indicating the sheet name.
Is CSV faster than XLSX for processing?
Yes, CSV is plain text and can be processed with fast, native tools. XLSX requires parsing compressed XML, which is slower.
Can I preserve formulas when converting to CSV?
No, CSV stores only the computed values, not the formulas. If you need formulas, keep the XLSX and process it with a library that supports formulas, like openpyxl with data_only=False.
What about CSV files with semicolons as delimiters?
Some locales use semicolons. Specify the delimiter in pandas with sep=';' or in csvkit with --delimiter ';'.
Should I use Python or shell tools for CSV processing?
For simple operations, shell tools are faster and more concise. For complex transformations, Python with pandas is more maintainable and robust.