Groovy脚本求助:按第三列值排序且A/B/C记录有序排列
Groovy脚本实现分号分隔数据的分组排序需求
需求说明
对分号分隔的文本行执行以下排序规则:
- 优先按第三列的值分组排序
- 同一分组内的记录,按第一列的
A→B→C固定顺序排列
输入示例
C;3456;12345685;xxxx;2021-09-17T00:00:00.000;tobefilled;;;;; C;3456;651326365;xxxx;2011-04-04T00:00:00.000;tobefilled;;;;; A;3456;12345685;298, Val Ste-Croix;;;;;;LUX;2055;Luxembourg;Dutch;;;;;; A;3456;651326365;;;;;;;;;;Dutch;;;;;; A;3456;456;;;;;;;LUX;;;Dutch;;;;;; A;3456;54321;;;;;;;BEL;4321;;Dutch;;;;;; A;3456;114;;;;;;;;;;Dutch;;;;;; B;3456;12345685;xxxx;;2021-09-17T00:00:00.000;M;;;;tobefilled;;;;tobefilled;;;;; B;3456;651326365;xxxx;;2011-04-04T00:00:00.000;F;;;;tobefilled;;;;tobefilled;;;;;
输出示例
A;3456;12345685;298, Val Ste-Croix;;;;;;LUX;2055;Luxembourg;Dutch;;;;; B;3456;12345685;xxxx;;2021-09-17T00:00:00.000;M;;;;tobefilled;;;;tobefilled;;;;; C;3456;12345685;xxxx;2021-09-17T00:00:00.000;tobefilled;;;;; A;3456;651326365;;;;;;;;;;Dutch;;;;;; B;3456;651326365;xxxx;;2011-04-04T00:00:00.000;F;;;;tobefilled;;;;tobefilled;;;;; C;3456;651326365;xxxx;2011-04-04T00:00:00.000;tobefilled;;;;; A;3456;456;;;;;;;LUX;;;Dutch;;;;;; A;3456;54321;;;;;;;BEL;4321;;Dutch;;;;;; A;3456;114;;;;;;;;;;Dutch;;;;;;
Groovy实现脚本
// 定义第一列的排序优先级,确保A在前、B居中、C最后 def columnPriority = ['A': 0, 'B': 1, 'C': 2] // 读取输入行(可替换为从文件读取:new File('input.txt').readLines()) def inputLines = """C;3456;12345685;xxxx;2021-09-17T00:00:00.000;tobefilled;;;;; C;3456;651326365;xxxx;2011-04-04T00:00:00.000;tobefilled;;;;; A;3456;12345685;298, Val Ste-Croix;;;;;;LUX;2055;Luxembourg;Dutch;;;;;; A;3456;651326365;;;;;;;;;;Dutch;;;;;; A;3456;456;;;;;;;LUX;;;Dutch;;;;;; A;3456;54321;;;;;;;BEL;4321;;Dutch;;;;;; A;3456;114;;;;;;;;;;Dutch;;;;;; B;3456;12345685;xxxx;;2021-09-17T00:00:00.000;M;;;;tobefilled;;;;tobefilled;;;;; B;3456;651326365;xxxx;;2011-04-04T00:00:00.000;F;;;;tobefilled;;;;tobefilled;;;;;""".readLines() // 核心排序逻辑 def sortedLines = inputLines.sort { lineA, lineB -> // 分割行并保留所有空列(split第二个参数-1的作用:不忽略末尾空字段) def colsA = lineA.split(';', -1) def colsB = lineB.split(';', -1) // 第一步:按第三列(索引2)分组排序 int groupComparison = colsA[2].compareTo(colsB[2]) if (groupComparison != 0) { return groupComparison } // 第二步:同组内按第一列的优先级排序 return columnPriority[colsA[0]] <=> columnPriority[colsB[0]] } // 输出排序后的结果 sortedLines.each { println it }
代码说明
split(';', -1):使用分号分割文本行时,强制保留末尾的空列,避免破坏原始数据的结构columnPriority映射:将A/B/C转换为数字优先级,数字越小排序越靠前,确保同组内严格遵循A→B→C的顺序sort闭包:先按第三列的字符串内容比较实现分组,同一分组内再按第一列的优先级排序- 输入读取可灵活替换:如果需要从文件读取数据,只需把
inputLines赋值为new File('你的输入文件路径').readLines()即可
内容的提问来源于stack exchange,提问作者piuser
相关产品推荐
相关产品推荐

