Groovy脚本为CSV字段加引号时出现多余空行求助
Groovy处理CSV添加引号时的格式问题修复
输入CSV文件
0123,00001,00001,01,4.00,T,H,xds,,,,,,,,,,,,,,, 1234,00001,00001,,TI,2024,,4956.00,0.00,,,,, 1234,00001,00001,,TI,2024,,4956.00,0.00,,,,,1234
现有Groovy脚本(存在问题)
def Message processData(Message message) { // Retrieve the body of the message as a string (assuming the CSV is in the message body) def body = message.getBody(String) // Split the body into lines def lines = body.split('\n') // Enclose each field in double quotes def quotedLines = lines.collect { line -> line.split(',').collect { field -> "\"${field}\"" }.join(',') } // Join the quoted lines back together def result = quotedLines.join('\n') // Set the modified body back to the message message.setBody(result) return message }
当前错误输出
"0123","00001","00001","01","4.00","T","H","xds","","","","","","","","","","","","","","","","\n " "1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","\n " "1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","1234"
期望输出
"0123","00001","00001","01","4.00","T","H","xds","","","","","","","","","","","","","","","" "1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","" "1234","00001","00001","","TI","2024","","4956.00","0.00","","","","","","1234"
问题分析与修复方案
问题根源:
- 原脚本仅用
split('\n')拆分,无法兼容Windows环境的\r\n换行符,还会在输入末尾有换行时生成空行,处理后变成无用的引号行。 - 输入行的换行/回车字符可能被错误混入字段,导致输出出现
\n这类异常字符。
修改后的脚本:
def Message processData(Message message) { def body = message.getBody(String) // 兼容Windows/Unix换行符,拆分后过滤空行(含全空格行) def lines = body.split(/\r?\n/).findAll { it.trim() != '' } def quotedLines = lines.collect { line -> line.split(',').collect { field -> // 清除字段中混入的换行/回车字符,避免输出异常 def cleanField = field.replaceAll(/[\r\n]/, '') "\"${cleanField}\"" }.join(',') } def result = quotedLines.join('\n') message.setBody(result) return message }
关键改动说明
- 用
split(/\r?\n/)拆分文本,同时支持Windows和Unix系统的换行格式。 - 增加
findAll { it.trim() != '' }过滤空行,避免无内容的行生成无效的引号行。 - 对每个字段执行
replaceAll(/[\r\n]/, ''),清除混入的换行/回车字符,解决输出中出现\n的问题。
内容的提问来源于stack exchange,提问作者janardhan d
相关产品推荐
相关产品推荐

