Search code examples
jmeterbeanshell

How to delete specific lines from a CSV file based on line number in beanshell scripting


Currently, I am trying to remove a specific line from a CSV file based on the line number.

Suppose I have a CSV file having below data:

Rakesh,1000,25,M
Gopi,2000,26,M
Shiva,3000,30,M
Gopi,5500,29,M
Tiru,4400,30,M
Ravi,3020,20,M

Also, I have an array which consists of some random number [2,5,6]

So instated of reading the entire file and writing it again I want to go to that specific line and remove that line completely.

Rakesh,1000,25,M
Shiva,3000,30,M
Gopi,5500,29,M

Code

 String fileData = FileUtils.readFileToString(csvFile);
    int lines = FileUtils.readLines(csvFile).size();
    log.info("Size:"+lines);
    ArrayList myList = new ArrayList();
    for (int i=1; i<lines; i++) {
                myList.add(i);
    }
    Collections.shuffle(myList);
    for (int i = 0; i < 100; i++) {
      log.info("Numebr:"+myList.get(i));
    }

    // Need to the line delete include that logic.

    FileUtils.writeStringToFile(output, fileData);

Solution

  • First of all Forget about Beanshell.

    Since JMeter 3.1 you should be using JSR223 test elements and Groovy language for scripting.

    The relevant Groovy script which removes the lines from the original file basing on the array of 1-based line numbers provided would be something like:

    def file = new File('test.csv')
    def originalLines = file.readLines()
    def array = [2, 5, 6]
    def newLines = []
    0.upto(originalLines.size() - 1, { index ->
        if (!array.contains(index + 1)) {
            newLines.add(originalLines.get(index))
        } else {
            array.removeElement(index)
        }
    })
    file.withWriter { w ->
        newLines.each { w.println it }
    }
    

    Demo:

    enter image description here