Reputation: 5674
Basically what I want to do is insert some extra code in to the output files from a 3rd party code generator and I need to insert in a few locations; the import section, fields, and at the end. It seems relatively easy to do using with / combinations and echoing to a file at the end, but the problem is in the field section as I can't guarantee it'll be the same number of lines before the Class declaration each time (if at any point anyone adds anything to the code that's generated the comment section the code generator spits out will be longer) and I don't want to risk inserting my field in the middle of something (any field could have annotations), so basically I'd like to match one of the fields that I know will always be there, find out what line that is on and insert after that.
So in short, is there any way I can use ant to find the line number matching a regular expression or string literal? (There will only be one if that makes things easier). Oh and the solution has to be cross-platform compatible as there are others accessing the code on Windows/Linux/Mac.
Upvotes: 2
Views: 1159
Reputation: 22867
You can use scripting (see scriptdef usage) language groovy
for example, or groovy
task to solve your problem.
I've prepared sample using groovy
script:
<target name="checkfile">
<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="libs"/>
<fileset id="files_to_search" dir="${folder.to.search}" includes="**/*.*"/>
<groovy>
ant.echo "Search for '${properties.str_to_find}' string"
project.references.files_to_search.each { fileResource ->
def file = new File(fileResource.toString())
def lines = 0
file.eachLine{
line ->
lines++;
if (line =~ /^${properties['str_to_find']}$/) println "Matches, line no: " + lines + ", file name: " + file;
}
}
</groovy>
</target>
My output:
checkfile:
Search for 'ddd' string
Matches, line no: 5, file name: d:\55\ouuu.txt
PS: I'm not groovy programmer, but this sample is working
Upvotes: 1
Reputation: 195289
sed can print line number easily. (by using "=")
e.g. sed -n '/yourPattern/=' yourfile
will print all all line numbers, that the lines match yourPattern.
sed - n '/yourPattern/{=;q}' yourFile
will print the line number of the 1st match line
do know if this is what you need.
AND, sed is platform independent. :D
Upvotes: 0