且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Ant脚本过滤器对行进行计数

更新时间:2023-01-20 16:52:20

您可以使用ant属性来保存静态".

You could use an ant property to hold the 'static'.

这是一个非常简化的示例,用于一个文件.

Here's a very simplified example, for one file.

<property name="lineNumber" value="0" />
<copy file="input.txt" tofile="output.txt" >
    <filterchain>
        <scriptfilter language="javascript">
            project.setProperty( "lineNumber", 
                                 parseInt( project.getProperty( "lineNumber" ) ) + 1 );

            if ( self.getToken().indexOf("__LINE__") != -1 ) {
                lineNumber = project.getProperty( "lineNumber" );
                self.setToken( self.getToken( ).replaceAll( "__LINE__", lineNumber ) );
            }               
        </scriptfilter>
    </filterchain>
</copy>

问题是:不会扩展到多个文件-lineNumber不会在文件之间重置为一个.

The problem is: that doesn't extend to multiple files - the lineNumber doesn't reset to one between files.

您可以使用 filetokenizer 来获取全部信息一次性将文件导入javascript,然后逐行处理该文件. 这是一个非常的点子示例(我知道足够多的javascript都是危险的).我确信这有很多错误(尤其是:它不处理非换行终止的文件;令人震惊的字符串连接). 但是原理是,通过将每个完整文件放入脚本中,您不需要任何信息即可在脚本调用之间持久化.

You might use a filetokenizer to get the whole file into javascript in one go, then process the file line-by-line. Here's a very noddy example (I know enough javascript to be dangerous). I'm sure this has lots of faults (not least: it doesn't handle non-newline terminated files; shocking string catenations). But the principle is that by getting each whole file into the script, you don't need any information to persist between script invocations.

<copy todir="output">
<fileset dir="input"/>
<filterchain>
    <tokenfilter>
    <filetokenizer/>
        <scriptfilter language="javascript"><![CDATA[

            // Get the whole input file to one string.
            inputContent = self.getToken( );

            lineNum = 1;
            fileEnd = inputContent.length( );

            // Build the new file up line-by-line in this var.
            outputContent = "";

            lineStart = 0;
            lineEnd = inputContent.indexOf( "\n" );
            while ( lineEnd < fileEnd ) {
                outputContent += inputContent
                                .substring( lineStart, lineEnd )
                                .replaceAll( "__LINE__", lineNum ) + "\n";
                lineStart = lineEnd + 1;
                fc = inputContent.substring( lineStart );
                lineEnd = fc.indexOf( "\n" );
                if ( lineEnd == -1 )
                    break;  
                lineEnd += lineStart;
                lineNum++;
            }

            self.setToken( outputContent );
           ]]></scriptfilter>
    </tokenfilter>
</filterchain>
</copy>