0

I am trying to find and replace string with another string in a file.

I have an XML file where port= is present at multiple locations. Every port has different value like port="443" and port="8011".

I want to find a particular port and its value. The current value of port is not known on batch execution as the value varies. This variable and on batch execution unknown value of one specific port attribute in the XML file should be replaced with a new value I am passing as a parameter to the batch file.

How can I find the particular port value from a file and replace it with a new value?

I have used the below code for replace string, but I am not able to change its value.

if EXIST %ConfPath% (echo "here") ELSE (
    for /f "tokens=1,* delims=¶" %%A in ( '"type %file%"' ) do (
        SET string=%%A

        SET modified=!string:%oldport%=%newport%!

        echo !modified! 
    )
)

Edit:

Here is my XML file:

<?xml version='1.0' encoding='utf-8'?> 
<Server port="first" shutdown="SHUTDOWN">  
<Listener className="org.apache.catalina.core.JasperListener" /> 
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" /> 
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" /> 
<GlobalNamingResources> 
<Resource name="UserDatabase" auth="Container" type="org.apache.catalina.UserDatabase" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml" /> 
</GlobalNamingResources> 
<Service name="Catalina">  
<Connector port="second" redirectPort="forth" /> 
<Connector port="third" protocol="HTTP/1.1" SSLEnabled="true" scheme="https" secure="true" clientAuth="false" sslProtocol="TLS" URIEncoding="UTF-8" keystoreFile="myKey" keystorePass="myPass" /> 
</Service> 
</Server> 

There are four ports present in above file.

I want to change port="third" with port="newPort".

Until now I have replaced the string, but I'm not able to concatenate it with the remaining file.

First I get the line number and after that I split with quotes and replace. But I I'm not able to concatenate it. Something is missing but I cannot find it.

My batch code is:

for /f "tokens=1,* delims=" %%A in ( '"type %file%"' ) do (
    SET /a line+=1
    IF !line!==11 (
        SET string=%%A
        for /f tokens^=2^ delims^=^" %%I in ( "!string!" ) do (set repPort=%%I)
        SET modified=!string:repPort=PORT!
    )
    echo !modified!
)

Is this the right approach and how can I concatenate?

Mofi
  • 38,783
  • 14
  • 62
  • 115
Tarun Sharma
  • 591
  • 3
  • 10
  • 29
  • 2
    To save time, here are the obligatory links for [jrepl.bat](http://www.dostips.com/forum/viewtopic.php?f=3&t=6044) and [GnuWin32 sed](http://gnuwin32.sourceforge.net/packages/sed.htm) that traditionally appear in these "How do I replace text in a text file" questions. – rojo Dec 22 '14 at 14:58
  • Did you try `>>newfile.xml echo !modified!`? Are you also intending to strip from ¶ to the end of the line on every line? – rojo Dec 22 '14 at 15:04
  • @rojo thnx rojo!! yes i am intending to strip to the end of the line on every line.Also i want to find and replace a particular text out of multiple text. – Tarun Sharma Dec 23 '14 at 04:22
  • @Mofi thxn mofi!! it is related to link that you have mentioned but not duplicate as i do not want to replace each occurrence with another but i want to replace a particular occurrence. – Tarun Sharma Dec 23 '14 at 04:33

1 Answers1

0

How can you find and replace text in a file using the Windows command-line environment? lists several tools for replacing a string in a file from command line.

I like free console tool xchang32.exe as it is powerful and very easy to use.

I copied the content of your XML file into a file and saved it with name Test.xml.

Then I executed following command:

xchang32.exe Test.xml "port=^34third^34 protocol" "port=^34newPort^34 protocol"

That command changed in the file only

<Connector port="third" protocol="HTTP/1.1" SSLEnabled="..." /> 

to

<Connector port="newPort" protocol="HTTP/1.1" SSLEnabled="..." /> 

^34 is an escape sequence for double quote character " which has decimal code value 34.

xchang32.exe /? entered and executed in a command prompt window outputs help for this replace tool.

Of course you could use also any other method suggested in the referenced topic. You just need to include protocol in search and replace string to modify just the port number which should be modified and ignore all other. Solutions using only Windows standard commands are more difficult because of the characters <, > and " in the XML file which have a special meaning on command line.


EDIT:

It is of course an important fact to know that the current port number in file is not known on executing the batch file. That was not really clear for me from the initial question. This makes it more difficult.

One solution would be to first search for existing port value and once found do the replace.

@echo off

rem Search in file for a line where first opening tag is
rem "Connector" which has as first attribute "port" and
rem one more attribute "protocol" and assign the value
rem of the attribute port to an environment variable.

for /F "tokens=1-4 delims==<     " %%A in (Test.xml) do (
    if "%%A"=="Connector" (
        if "%%B"=="port" (
            if "%%D"=="protocol" (
                set "PortNumber=%%~C"
                goto Replace
            )
        )
    )
)
echo Could not find the port value of interest.
goto :EOF

:Replace
xchang32.exe Test.xml "port=^34,%PortNumber%^34 protocol" "port=^34,%~1^34 protocol"
set "PortNumber="

Attention:

There are 4 characters after delims= on line with command for:

  1. an equal sign,
  2. a left angle bracket,
  3. a horizontal tab character (not a sequence of spaces as browser displays) and
  4. a single space character.

The order of the delimiter characters is important as otherwise command line interpreter would exit batch script because of a syntax error.

The line of interest is split up by command for with those 4 delimiters into:

  • token 1: Connector
  • token 2: port
  • token 3: "third"
  • token 4: protocol
  • and more tokens not of interest.

Those 4 tokens are assigned to the loop variables A (tag name), B (name of first attribute), C (value of first attribute) and D (name of second attribute.

The values of variables A, B and D are used to check if the right line was found. The value of variable C is assigned on positive check to an environment variable with removing the surrounding double quotes. Then the loop is exited with a jump to replace part of the batch script.

Again free tool xchang32.exe is used to make the replacement in the file without changing anything else. As the value assigned to attribute port is an integer value, it is necessary to use a comma after first ^34 to let the tool know where the integer number referencing the double quote character ends.

For help on command for execute in a command prompt window either for /? or help for.

Community
  • 1
  • 1
Mofi
  • 38,783
  • 14
  • 62
  • 115
  • but there is one more thing that third is a dynamic variable and i dont know about it. so how am i able to do that now? – Tarun Sharma Dec 23 '14 at 07:47