Okky
Okky

Reputation: 10466

How to split a list by comma in bash script

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?

Upvotes: 2

Views: 202

Answers (1)

chiastic-security
chiastic-security

Reputation: 20520

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.

Upvotes: 2

Related Questions