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

查看:435
本文介绍了如何在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:

read x y < <(echo a b)

$ y是b.为什么?

推荐答案

您需要使用IFS而不是-d:

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

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

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天全站免登陆