如何通过脚本实现按指定分隔符提取含特殊字符的CSV列?
Absolutely! This is a super common pain point with CSV files—when fields have commas inside quotes or line breaks, naive splitting on commas breaks everything. The good news is scripting this is totally doable, and there are clean, reliable solutions using tools built specifically for handling CSV structure.
Let’s walk through a few options depending on what tools you’re comfortable with:
Python (Most Flexible)
Python’s built-in csv module was made exactly for this scenario—it automatically handles quoted fields, even when they contain commas or line breaks. Here’s a quick script to extract your target columns:
import csv # Replace 'input.csv' with your actual file path with open('input.csv', 'r', newline='', encoding='utf-8') as input_file: # The csv.reader will parse fields correctly, respecting quotes csv_reader = csv.reader(input_file) # Optional: if you want to write the extracted columns to a new CSV with open('output.csv', 'w', newline='', encoding='utf-8') as output_file: csv_writer = csv.writer(output_file) for row in csv_reader: # Python uses 0-indexing, so columns 1,2,5 from your question are index 0,1,4 extracted = [row[0], row[1], row[4]] csv_writer.writerow(extracted) # Or just print to console if you don't need a file: # print(",".join(extracted))
This will correctly handle all those edge cases in your CSV—no more mangled fields!
Command Line (Quick & No Script Writing)
If you prefer staying in the terminal, use csvkit—a handy set of command-line tools for CSV processing. First install it via pip install csvkit, then run:
csvcut -c 1,2,5 input.csv > output.csv
csvcut understands CSV structure natively, so it’ll parse quoted fields properly without any extra work from you.
Awk (For Command Line Purists)
If you want to use awk (no extra installs), you can define a field pattern that respects quoted fields. Add this to your terminal:
awk 'BEGIN {FPAT = "([^,]*)|(\"[^\"]+\")"} {print $1 "," $2 "," $5}' input.csv > output.csv
The FPAT variable tells awk to recognize fields as either strings without commas, or strings wrapped in double quotes—this bypasses the naive comma split.
All these methods work way better than manual Excel work, especially if you need to process multiple files or automate the task.
内容的提问来源于stack exchange,提问作者JChetan

