Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Split CSV

Tags:

split

csv

groovy

I have a csv file (details.csv) like

ID,NAME,ADDRESS
1,"{foo,bar}","{123,mainst,ny}"
2,"{abc,def}","{124,mainst,Va}"
3,"{pqr,xyz}","{125,mainst,IL}"

when I use (Note: I have other closure above this which reads all csv files from directory)

if(file.getName().equalsIgnoreCase("deatails.csv")) {
 input = new FileInputStream(file)
 reader = new BufferedReader(new InputStreamReader(input))
 reader.eachLine{line-> def cols = line.split(",")
 println cols.size() }

Instead of getting size 3 I am getting 6 with values

1
"{foo
bar}"
"{123
mainst
ny}"

spilt(",") is splitting data by comma(,) but I want my results as

1
"{foo,bar}"
"{123,mainst,ny}"

How can I fix this closure. Please help! Thanks

like image 684
springpress Avatar asked Nov 30 '22 14:11

springpress


1 Answers

Writing a csv parser is a tricky business.

I would let someone else do the hard work, and use something like GroovyCsv


Here is how to parse it with GroovyCsv

// I'm using Grab instead of just adding the jar and its
// dependencies to the classpath
@Grab( 'com.xlson.groovycsv:groovycsv:1.0' )
import com.xlson.groovycsv.CsvParser

def csv = '''ID,NAME,ADDRESS
1,"{foo,bar}","{123,mainst,ny}"
2,"{abc,def}","{124,mainst,Va}"
3,"{pqr,xyz}","{125,mainst,IL}"'''

def csva = CsvParser.parseCsv( csv )
csva.each {
  println it
}

Which prints:

ID: 1, NAME: {foo,bar}, ADDRESS: {123,mainst,ny}
ID: 2, NAME: {abc,def}, ADDRESS: {124,mainst,Va}
ID: 3, NAME: {pqr,xyz}, ADDRESS: {125,mainst,IL}

So, to get the NAME field of the second row, you could do:

def csvb = CsvParser.parseCsv( csv )
println csvb[ 1 ].NAME

Which prints

{abc,def}

Of course, if the CSV is a File, you can do:

def csvc = new File( 'path/to/csv' ).withReader {
  CsvParser.parseCsv( it )
}

Then use it as above

like image 107
tim_yates Avatar answered Dec 04 '22 16:12

tim_yates