2

I was trying to read a csv file and split the data by comma.

I used

IFS=, list=($line)
for word in ${list[@]}; do
  echo $word
done

to split the csv record based on comma, which works fine.

The issue is when I have a quoted string in the csv which contains a comma

Name, "Oct 2, 2015 at 1:06 PM", Superman

In this scenario it returns

Name
"Oct 2
 2015 at 1:06 PM"
Superman

Whereas I want

Name
"Oct 2, 2015 at 1:06 PM"
Superman

How to solve this?

fedorqui
  • 275,237
  • 103
  • 548
  • 598
Okky
  • 10,338
  • 15
  • 75
  • 122

1 Answers1

2

There isn't a good way to do this in pure bash, and you can't use cut to do it, which also doesn't respect quotes.

There are good command-line utilities around that do it, though. Fedora has a csv package, for instance, that provides a csv command that does the same sort of thing as cut but respecting quotes:

[james@marlon ~] $ echo '1,"3,w",4' | csv --col 2
"3,w"

It also provides a package ocaml-csv, which gives you csvtool with similar functionality:

[james@marlon ~] $ echo '1,"3,w",4' | csvtool col 2 -
"3,w"

These are very likely to be available on other distros too.

chiastic-security
  • 20,430
  • 4
  • 39
  • 67