有没有一种方法来创建一个CSV文件,其中包括另外两列连接用加入了一个新列"-"
-使用Ant?
例:
customer,deal,NEWFIELD
200000042,23,200000042-23
200000042,34,200000042-34
200000042,35,200000042-35
200000042,65,200000042-65
有没有一种方法来创建一个CSV文件,其中包括另外两列连接用加入了一个新列"-"
-使用Ant?
例:
customer,deal,NEWFIELD
200000042,23,200000042-23
200000042,34,200000042-34
200000042,35,200000042-35
200000042,65,200000042-65
难道是简单的使嵌入的脚本语言如Groovy?
├── build.xml
├── src
│ └── file1.csv
└── target
└── file1.csv
customer,deal
200000042,23
200000042,34
200000042,35
200000042,65
customer,deal,customer-deal
200000042,23,200000042-23
200000042,34,200000042-34
200000042,35,200000042-35
200000042,65,200000042-65
<project name="demo" default="build">
<available classname="org.codehaus.groovy.ant.Groovy" property="groovy.installed"/>
<target name="build" depends="install-groovy">
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
<groovy>
ant.mkdir(dir:"target")
new File("target/file1.csv").withWriter {
new File("src/file1.csv").splitEachLine(",") { customer, deal ->
it.println "${customer},${deal},${customer}-${deal}"
}
}
</groovy>
</target>
<target name="install-groovy" description="Install groovy" unless="groovy.installed">
<mkdir dir="${user.home}/.ant/lib"/>
<get dest="${user.home}/.ant/lib/groovy.jar" src="http://search.maven.org/remotecontent?filepath=org/codehaus/groovy/groovy-all/2.4.7/groovy-all-2.4.7.jar"/>
<fail message="Groovy has been installed. Run the build again"/>
</target>
</project>
您可以使用Ant做到这一点filterchains ,像这样简单的例子:
<property name="in.file" value="input.txt" />
<property name="out.file" value="output.txt" />
<property name="new.field" value="NEWFIELD" />
<property name="sep.char" value="," />
<loadfile srcfile="${in.file}" property="file.head">
<filterchain>
<headfilter lines="1" />
<striplinebreaks />
</filterchain>
</loadfile>
<loadfile srcfile="${in.file}" property="file.body">
<filterchain>
<headfilter skip="1" />
<tokenfilter>
<replaceregex pattern="^([^${sep.char}]*)${sep.char}([^${sep.char}]*)$"
replace="\1${sep.char}\2${sep.char}\1-\2" />
</tokenfilter>
</filterchain>
</loadfile>
<echo file="${out.file}">${file.head}${sep.char}${new.field}
${file.body}</echo>
两个<loadfile>
任务用于处理该文件的头部和身体,然后进行简单<echo>
任务写入的输出。 一个简单的正则表达式的工作原理这里领域的CSV文件的数量较少。 该replaceregex
采用捕获组拿到就行了前两个字段,然后在replace
字符串组装所需的输出。
如果有几个字段,那么也许一个scriptfilter
在第二loadfile
会傻笑一起工作:
<loadfile srcfile="${in.file}" property="file.body">
<filterchain>
<headfilter skip="1" />
<scriptfilter language="javascript"><![CDATA[
var line = self.getToken( );
var fields = line.split( "," );
self.setToken( line + "," + fields[0] + "-" + fields[1] );
]]></scriptfilter>
</filterchain>
</loadfile>
这一个取线,分割它,然后追加必填字段。
无论举例来说,如果您的数据包含嵌入的逗号这里会工作。