I am creating an ANT script for which I am using a fileset and a regex to get my file and to get an expression in that file.
I also need to store the expression in a spreadsheet, which I am not sure how to do it.
I have learned somewhere that I could use replaceregexp, but I am not sure how do I do that.
I have used target tasks to do the search for the file and expression.
ANT is not a programming language so this is not a trivial problem to solve. The following example uses:
- groovy task implement the parsing logic
- Apache POI to write the excel file
- Apache ivy to manage the 3rd party jar dependencies.
Example
This is example counts the number of occurrences of the string "one" in the resources sub directory:
├── build.xml
├── resources
│ ├── file1.txt
│ ├── file2.txt
│ └── file3.txt
└── results.xlsx
Results are also written to an excel file "results.xlsx"
parse-files:
[groovy] File:file1.txt Count:1
[groovy] File:file2.txt Count:0
[groovy] File:file3.txt Count:1
build.xml
<project name="demo" default="parse-files" xmlns:ivy="antlib:org.apache.ivy.ant">
<available classname="org.apache.ivy.Main" property="ivy.installed"/>
<target name="parse-files" depends="init" >
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="groovy.path"/>
<fileset dir="resources" id="filesToParse" includes="*.txt"/>
<groovy>
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.ss.usermodel.CreationHelper
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Row
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Regexp results");
CreationHelper helper = wb.getCreationHelper();
rowpos = 0
project.references.filesToParse.each {
def file = it.file
def content = file.text
// Search file
def findOneStr = content =~ /one/
println "File:${file.name} Count:${findOneStr.count}"
// Save to Excel row
Row row = sheet.createRow(rowpos++)
row.createCell(0).setCellValue(helper.createRichTextString(file.name));
row.createCell(1).setCellValue(findOneStr.count);
}
// Save excel file
new File("results.xlsx").withOutputStream {
wb.write(it)
}
</groovy>
</target>
<target name="init" depends="install-ivy" description="Resolve dependencies">
<ivy:cachepath pathid="groovy.path">
<dependency org="org.codehaus.groovy" name="groovy-all" rev="2.4.3" conf="default"/>
<dependency org="org.apache.poi" name="poi-ooxml" rev="3.10.1" conf="default"/>
</ivy:cachepath>
</target>
<target name="install-ivy" description="Install ivy" unless="ivy.installed">
<mkdir dir="${user.home}/.ant/lib"/>
<get dest="${user.home}/.ant/lib/ivy.jar" src="http://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.4.0/ivy-2.4.0.jar"/>
<fail message="Ivy has been installed. Run the build again"/>
</target>
</project>