使用 Ant 就地过滤文件? [英] Filtering Files In-Place with Ant?
问题描述
我有一个文件目录,我想使用 Apache Ant(Linux 上的 1.7.1 版)对其进行就地"字符串过滤.
I have a directory of files for which I'd like to do "in-place" string filtering using Apache Ant (version 1.7.1 on Linux).
例如,假设在目录 mydir
中有文件 foo
、bar
和 baz
.进一步假设正则表达式 OLD([0-9])
的所有出现都应该更改为 NEW\1
,例如OLD2
→NEW2
.(请注意,replace
Ant 任务将不起作用,因为它不支持正则表达式过滤.)
For example, suppose that in directory mydir
I have files foo
, bar
, and baz
. Further suppose that all occurences of the regular expression OLD([0-9])
should be changed to NEW\1
, e.g. OLD2
→ NEW2
. (Note that the replace
Ant task won't work because it does not support regular expression filtering.)
这个测试场景可以用下面的 Bash 命令来创建(ant 会运行在当前目录,即 mydir
的父目录):
This test situation can be created with the following Bash commands (ant will be run in the current directory, i.e. mydir
's parent directory):
mkdir mydir
for FILE in foo bar baz ; do echo "A OLD1 B OLD2 C OLD3" > mydir/${FILE} ; done
这是我第一次尝试用 Ant 进行过滤:
Here is my first attempt to do the filtering with Ant:
<?xml version="1.0"?>
<project name="filter" default="filter">
<target name="filter">
<move todir="mydir">
<fileset dir="mydir"/>
<filterchain>
<tokenfilter>
<replaceregex pattern="OLD([0-9])" replace="NEW\1" flags="g"/>
</tokenfilter>
</filterchain>
</move>
</target>
</project>
运行第一个 Ant 脚本对 mydir
中的文件没有影响.overwrite
参数在 move
Ant 任务中默认为 true
.我什至摆弄了 granularity
设置,但这没有帮助.
Running this first Ant script has no effect on the files in mydir
. The overwrite
parameter is true
by default with the move
Ant task. I even fiddled with the granularity
setting, but that didn't help.
这是我的第二次尝试,它有效",但由于临时文件创建而有点烦人.此版本通过将内容移动到带有 filtered
后缀的文件来正确过滤内容,然后过滤后的内容会以原始文件名移回":
Here's my second attempt, which "works," but is slightly annoying because of temporary file creation. This version filters the content properly by moving the content to files with a filtered
suffix, then the filtered content is "moved back" with original filenames:
<?xml version="1.0"?>
<project name="filter" default="filter">
<target name="filter">
<move todir="mydir">
<globmapper from="*" to="*.filtered"/>
<fileset dir="mydir"/>
<filterchain>
<tokenfilter>
<replaceregex pattern="OLD([0-9])" replace="NEW\1" flags="g"/>
</tokenfilter>
</filterchain>
</move>
<move todir="mydir">
<globmapper from="*.filtered" to="*"/>
<fileset dir="mydir"/>
</move>
</target>
</project>
第一次尝试(没有临时文件)可以工作吗?
推荐答案
参见 replace 任务:
<replace
dir="mydir"
includes="foo, bar, baz">
<replacefilter token="OLD" value="NEW" />
</replace>
或replaceregexp 任务:
<replaceregexp
file="${src}/build.properties"
match="OldProperty=(.*)"
replace="NewProperty=\1"
byline="true"/>
这篇关于使用 Ant 就地过滤文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!