user1037728
user1037728

Reputation: 133

trouble using replaceregexp when replacing string DIR location

I am having trouble in doing this. there is 1 batch file with this line:

set TEST_DIR=C:\temp\dir1

I just want to set some new value to TEST_DIR

But, when I use in my ant script, it escapes forward slashes and gives this result:

set TEST_DIR=C:homedir2

Instead, I want to give it:

set TEST_DIR=C:\home\dir2

I am using this command:

<replaceregexp file="${MT_BATCH_FILE_LOCATION}\myfile.bat" match="TEST_DIR=C:\\temp\\dir1" replace="TEST_DIR=C:\home\dir2" byline="true" />

Upvotes: 3

Views: 5968

Answers (2)

user1037728
user1037728

Reputation: 133

I have found another simple solution use replace instead of replaceregexp.

<replace file="${MT_BATCH_FILE_LOCATION}\myfile.bat"
                            token='TEST_DIR=C:\temp\dir1'
                    value='TEST_DIR=${new_loc}\home\dir2' />

Upvotes: 5

ewan.chalmers
ewan.chalmers

Reputation: 16235

You can get the result you want by using this replace pattern:

 replace="TEST_DIR=C:\\\\home\\\\dir2"

The reason is that you must escape the backslash once for the regex and once for Java - backslash is an escape character in both those contexts.

In answer to your subsequent questions in comments...

  1. I expect the answer will be the same. You will need to double-escape the backslash in the value of ${new_loc}, i.e. use C:\\\\my_projcode not C:\my_projcode.

  2. If new_loc is coming in as an environment variable, you could use the propertyregex task from ant-contrib to escape backslashes in the value:

    <project default="test">
    
      <!-- import ant-contrib --> 
      <taskdef resource="net/sf/antcontrib/antlib.xml">
        <classpath>
          <pathelement location="C:/lib/ant-contrib/ant-contrib-1.0b3.jar"/>
        </classpath>
      </taskdef>
    
      <target name="test">
    
        <!-- load environment variables -->
        <property environment="env"/>
    
        <!-- escape backslashes in new_loc -->
        <propertyregex property="loc" input="${env.new_loc}" regexp="\\" replace="\\\\\\\\\\\\\\\\" />
    
        <echo message="env.new_loc: ${env.new_loc}"/>
        <echo message="loc: ${loc}"/>
    
        <!-- do the replace --> 
        <replaceregexp file="test.bat" match="TEST_DIR=C:\\temp\\dir1" replace="TEST_DIR=${loc}\\\\home\\\\dir2" byline="true" />
    
      </target>
    

Output:

c:\tmp\ant>set new_loc=c:\foo\bar

c:\tmp\ant>ant
Buildfile: c:\tmp\ant\build.xml

test:
     [echo] new_loc: c:\foo\bar
     [echo] env.new_loc: c:\foo\bar
     [echo] loc: c:\\\\foo\\\\bar

BUILD SUCCESSFUL
Total time: 0 seconds

c:\tmp\ant>type test.bat
set TEST_DIR=c:\foo\bar\home\dir2

Upvotes: 7

Related Questions