Quotes appearing on CSV after concatnate fields using Groovy

后端 未结 1 862
渐次进展
渐次进展 2021-01-23 10:26

I\'m using groovy to concatenate two fields in CSV It\'s working ok except that the concatenated field is appearing with quotes.

Is there any way to resolve this?

<
1条回答
  •  不要未来只要你来
    2021-01-23 11:12

    CSV is a more complicated file format than it would first appear. Fields can be optionally quoted which is what appears to be your problem.

    Most programming languages have a library that will parse CSV. In the case of groovy I'd recommend opencsv

    http://opencsv.sourceforge.net/

    The following example extends the example I created for your previous question.

    Example

    ├── build.xml
    ├── src
    │   └── file1.csv
    └── target
        └── file1.csv
    

    src/file1.csv

    "customer",deal
    "200000042",23
    "200000042",34
    "200000042",35
    "200000042",65
    

    target/file1.csv

    customer,deal,customer-deal
    200000042,23,200000042-23
    200000042,34,200000042-34
    200000042,35,200000042-35
    200000042,65,200000042-65
    

    build.xml

    
    
      
    
      
        
    
        
          import com.opencsv.CSVReader
    
          ant.mkdir(dir:"target")
    
          new File("target/file1.csv").withWriter { writer ->
            new File("src/file1.csv").withReader { reader ->
              CSVReader csv = new CSVReader(reader);
    
              csv.iterator().each { row ->
                if (row.size() == 2) {
                  writer.println "${row[0]},${row[1]},${row[0]}-${row[1]}"
                }
              }
            }
          }
        
      
    
       
        
          
          
        
      
    
      
        
        
        
      
    
    
    

    Notes:

    • Uses apache ivy to managed dependencies like groovy and opencsv
    • I included a test "row.size() == 2" to prevent empty rows throwing errors

    0 讨论(0)
提交回复
热议问题