brucmao
brucmao

Reputation: 13

jmeter - how to creat new csv from original csv with groovy

I have a csv file (UTF-8 with BOM) like this

NAME,F1,F2,
test1,field1,field2
test2,field1,field2
test3,field1,field2
test4,field1,field2
test5,field1,field2
test6,field1,field2

I would like to discard the first three lines and create new csv (UTF-8 with BOM)

NAME,F1,F2,
test4,field1,field2
test5,field1,field2
test6,field1,field2

I get some idea from the page and code this in JSR223 PreProcessor

def originalCsvFile = new File('g:/Workspace/1.csv')
def newCsvFile = new File('g:/Workspace/2.csv')


originalCsvFile.readLines().take(5).each {line ->
    newCsvFile.withWriter('UTF-8') { writer ->   
        writer.writeLine line
    }
  }

The above code does not work. It is better to put the new csv path to the variable, I want to get the variable in jmeter CSV Data Set Config

Upvotes: 0

Views: 439

Answers (2)

ou_ryperd
ou_ryperd

Reputation: 2133

Not as elegant, perhaps, but this is how I would do it:

List li = originalCsvFile.readLines()
newCsvFile.append(li[0] + "\n", 'UTF-8') //headers
li[4..-1].each { newCsvFile.append(it + "\n", 'UTF-8') }

Upvotes: 0

Dmitri T
Dmitri T

Reputation: 168157

Do you realize that:

  1. take(5) function returns 5 first lines of the list
  2. newCsvFile.withWriter function overwrites the file with the new data each time it's being called

So I believe you're looking for copying and pasting something like this:

originalCsvFile.readLines().eachWithIndex { line, index ->
    if (index == 0 || index > 3) {
        newCsvFile.withWriterAppend('UTF-8') { writer ->
            writer.writeLine line
        }
    }
}

More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Upvotes: 1

Related Questions