如何结合文本限定符使用cut命令提取CSV指定列
Ah, I feel your pain—cut is super handy for simple delimited data, but it completely ignores CSV's quoted field rules. That's why it's chopping your "1,2,3" into just "1" when you use -d',' -f2.
The good news is there are several reliable ways to handle this properly. Here are the most practical methods:
1. Use a CSV-aware awk script
awk can be modified to track whether we're inside a quoted field, so it skips commas within quotes. Here's a one-liner that does exactly what you need:
awk -F',' '{ in_quote = 0 current_col = "" for (i=1; i<=NF; i++) { current_col = current_col $i # Toggle quote state if this field has an odd number of quotes if (gsub(/"/, "", $i) % 2 != 0) { in_quote = !in_quote } # If we're not in quotes and we've reached column 2, print and exit loop if (!in_quote && i == 2) { print current_col break } # If we're still in quotes, add back the comma we split on else if (in_quote) { current_col = current_col "," } } }' xyz.txt
This will output "1,2,3" (keeping the quotes). If you want to strip the quotes, change the print line to:
print gensub(/^"|"$/, "", "g", current_col)
2. Use csvkit (the easiest dedicated CSV tool)
If you can install external tools, csvkit is built for exactly this scenario. Install it via your package manager:
- Debian/Ubuntu:
sudo apt install csvkit - macOS:
brew install csvkit - Windows:
pip install csvkit
Then extract the second column with:
csvcut -c 2 xyz.txt
By default, this outputs 1,2,3 (without quotes). To keep the quotes, add the --keep-quotes flag:
csvcut -c 2 --keep-quotes xyz.txt
3. Quick sed hack (for simple cases)
If your CSV is as straightforward as your example, a sed command can work—though it's less robust for edge cases (like escaped quotes inside fields):
# Keep quotes sed -E 's/^[^,]*,("[^"]*").*/\1/' xyz.txt # Remove quotes sed -E 's/^[^,]*,\"([^\"]*)\"(.*)/\1/' xyz.txt
Why cut fails here
cut treats every comma as a separator, no exceptions. So when it processes A,"1,2,3",C,D, it splits the line into these fields:
A"123"CD
That's why-f2gives you"1"instead of the full quoted field.
内容的提问来源于stack exchange,提问作者P S

