如何在groovy脚本/ nifi中将两行数据合并为单行?

时间:2017-08-16 13:01:04

标签: groovy apache-nifi

我的数据采用非结构化数据的形式,其中列的结尾存储在两行中,如下所示。

UID|Name|ID|Mail
1|Ester|991|sd
gmail
2|Siva|992|siva
hotmail
3|Hari|993|hi gmail

数据中的某些行已经完成,但有些行可以避免这两行数据变成单行,如下所示。

UID|Name|ID|Mail
1|Ester|991|sd gmail
2|Siva|992|siva hotmail
3|Hari|993|hi gmail

我不知道nifi处理器对这种转换很有帮助。

但是我尝试使用Groovy Script来读取行并且无法找到将spitted行组合成单行的方法。

def flowfile = session.get()
if(!flowfile)return
flowfile = session.write(flowfile, {rawIn, rawOut->
    // ## transform streams into reader and writer
    rawIn.withReader("UTF-8"){reader->
        rawOut.withWriter("UTF-8"){writer->
            reader.eachLine{line, lineNum->
                    if(!line.isEmpty())
                    {// ## let use regular expression to transform each line
                    writer << line << '\n'
                }
            }
        }
    }
} as StreamCallback)
session.transfer(flowfile, REL_SUCCESS) 

任何人都可以建议我将数据转换为需求吗?

1 个答案:

答案 0 :(得分:3)

我假设带标题的第一行不能有新的行符号并提供分隔符数

以下几行只是检查分隔符的数量,并决定是否写新行。

但如果您在最后一栏中有新行,则此算法将有效...

代码段:

def reader = new StringReader('''UID|Name|ID|Mail
1|Ester|991|sd
gmail
2|Siva|992|siva
hotmail
3|Hari|993|hi gmail''')

def writer = new StringWriter()

def delimCount = 0
reader.eachWithIndex{line,id->
    if(id==0){
        //let's count delims in header
        delimCount = line.count('|')
        //write header as is
        writer << line
    }else{
        if( line.count('|')==delimCount ){
            writer << '\n' //write new line
        }else{
            writer << ' ' //write space to continue previous line
        }
        writer << line
    }
}

println writer.toString()

结果:

UID|Name|ID|Mail
1|Ester|991|sd gmail
2|Siva|992|siva hotmail
3|Hari|993|hi gmail