Replacing characters in Ant property

2019-01-03 13:29发布

Is there a simple way of taking the value of a property and then copy it to another property with certain characters replaced?

Say propA=This is a value. I want to replace all the spaces in it into underscores, resulting in propB=This_is_a_value.

标签: string ant
10条回答
Animai°情兽
2楼-- · 2019-01-03 14:04

If ant-contrib isn't an option, here's a portable solution for Java 1.6 and later:

<property name="before" value="This is a value"/>
<script language="javascript">
    var before = project.getProperty("before");
    project.setProperty("after", before.replaceAll(" ", "_"));
</script>
<echo>after=${after}</echo>
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 14:06

Use some external app like sed:

<exec executable="sed" inputstring="${wersja}" outputproperty="wersjaDot">
  <arg value="s/_/./g"/>
</exec>
<echo>${wersjaDot}</echo>

If you run Windows get it googling for "gnuwin32 sed".

The command s/_/./g replaces every _ with . This script goes well under windows. Under linux arg may need quoting.

查看更多
狗以群分
4楼-- · 2019-01-03 14:08

Here's a more generalized version of Uwe Schindler's answer:

You can use a macrodef to create a custom task.

<macrodef name="replaceproperty" taskname="@{taskname}">
    <attribute name="src" />
    <attribute name="dest" default="" />
    <attribute name="replace" default="" />
    <attribute name="with" default="" />
    <sequential>
        <loadresource property="@{dest}">
            <propertyresource name="@{src}" />
            <filterchain>
                <tokenfilter>
                    <filetokenizer/>
                    <replacestring from="@{replace}" to="@{with}"/>
                </tokenfilter>
            </filterchain>
        </loadresource>
    </sequential>
</macrodef>

you can use this as follows:

<replaceproperty src="property1" dest="property2" replace=" " with="_"/>

this will be pretty useful if you are doing this multiple times

查看更多
smile是对你的礼貌
5楼-- · 2019-01-03 14:09

In case you want a solution that does use Ant built-ins only, consider this:

<target name="replace-spaces">
    <property name="propA" value="This is a value" />
    <echo message="${propA}" file="some.tmp.file" />
    <loadfile property="propB" srcFile="some.tmp.file">
        <filterchain>
            <tokenfilter>
                <replaceregex pattern=" " replace="_" flags="g"/>
            </tokenfilter>
        </filterchain>
    </loadfile>
    <echo message="$${propB} = &quot;${propB}&quot;" />
</target>

Output is ${propB} = "This_is_a_value"

查看更多
登录 后发表回答