如何根据 beanshell 脚本中的行号从 CSV 文件中删除特定行
How to delete specific lines from a CSV file based on line number in beanshell scripting
目前,我正在尝试根据行号从 CSV 文件中删除特定行。
假设我有一个包含以下数据的 CSV 文件:
Rakesh,1000,25,M
Gopi,2000,26,M
Shiva,3000,30,M
Gopi,5500,29,M
Tiru,4400,30,M
Ravi,3020,20,M
此外,我有一个由一些随机数组成的数组 [2,5,6]
所以开始读取整个文件并再次写入我想转到该特定行并完全删除该行。
Rakesh,1000,25,M
Shiva,3000,30,M
Gopi,5500,29,M
代码
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);
Since JMeter 3.1 you should be using JSR223 test elements and Groovy language 用于脚本。
根据提供的基于 1 的行号数组从原始文件中删除行的相关 Groovy 脚本类似于:
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 }
}
演示:
目前,我正在尝试根据行号从 CSV 文件中删除特定行。
假设我有一个包含以下数据的 CSV 文件:
Rakesh,1000,25,M
Gopi,2000,26,M
Shiva,3000,30,M
Gopi,5500,29,M
Tiru,4400,30,M
Ravi,3020,20,M
此外,我有一个由一些随机数组成的数组 [2,5,6]
所以开始读取整个文件并再次写入我想转到该特定行并完全删除该行。
Rakesh,1000,25,M
Shiva,3000,30,M
Gopi,5500,29,M
代码
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);
Since JMeter 3.1 you should be using JSR223 test elements and Groovy language 用于脚本。
根据提供的基于 1 的行号数组从原始文件中删除行的相关 Groovy 脚本类似于:
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 }
}
演示: