如何在 Bash 中解析 CSV 文件? [英] How to parse a CSV file in Bash?

查看:45
本文介绍了如何在 Bash 中解析 CSV 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个很长的 Bash 脚本.我想将 CSV 文件中的单元格读取到 Bash 变量中.我可以解析行和第一列,但不能解析任何其他列.到目前为止,这是我的代码:

I'm working on a long Bash script. I want to read cells from a CSV file into Bash variables. I can parse lines and the first column, but not any other column. Here's my code so far:


  cat myfile.csv|while read line
  do
    read -d, col1 col2 < <(echo $line)
    echo "I got:$col1|$col2"
  done

它只打印第一列.作为附加测试,我尝试了以下操作:

It's only printing the first column. As an additional test, I tried the following:

read -d, x y <<(echo a,b,)

$y 是空的.所以我尝试了:

And $y is empty. So I tried:

读取 x y <<(echo a b)

而 $y 是 b.为什么?

And $y is b. Why?

推荐答案

你需要使用IFS代替-d:

while IFS=, read -r col1 col2
do
    echo "I got:$col1|$col2"
done < myfile.csv

请注意,对于通用 CSV 解析,您应该使用专门的工具,该工具可以处理带内部逗号的引用字段,以及 Bash 本身无法处理的其他问题.此类工具的示例是 cvstoolcsvkit.

Note that for general purpose CSV parsing you should use a specialized tool which can handle quoted fields with internal commas, among other issues that Bash can't handle by itself. Examples of such tools are cvstool and csvkit.

这篇关于如何在 Bash 中解析 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆