Wokoman
Wokoman

Reputation: 1129

How to replace & with & in a batch file?

[EDIT] Added full example to show exact problem [/EDIT]

I'm sanitizing some log files so I can convert them to XML, and all works fine except for some of the non XML compliant characters that are in the log files.

I was therefore trying to replace & with &.amp; (remove the dot) , but somehow this seems to be a problem.

This is my bat file :

@echo off & setLocal enableDELAYedexpansion

set "find=&"
set "replace=&"

findstr /v "string1 string2" test.log > tmp_test.log
> test.xml (
  echo ^<rows^>
  for /f "tokens=5" %%A in (tmp_test.log) do (
  set string=%%A
  call set string=%%string:!find!=!replace!%%
  echo ^<r a="!string!"/^>
  )
  echo ^</rows^>
)
del tmp_test.log
endlocal

This is a simplified log file, basic idea is to get the 5th token (the URI) remove some redundant ones (containing string1 or string2), replace XML non-compliant characters and save it as an XML file.

2014-03-27 00:00:12 123.45.67.890 GET /good_url.html?something=one&something_else=four - 8080
2014-03-27 00:00:12 123.45.67.890 GET /good_url.html - 8080
2014-03-27 00:00:12 123.45.67.890 GET /string2.html - 8080
2014-03-27 00:00:13 123.45.67.890 GET /string1.html - 8080
2014-03-27 00:00:13 123.45.67.890 GET /some_uri_with_html/%2e%2e%2f%2eini - 8080

And this is the output :

<rows>
<r a="/good_url.html?something=one&something_else=four"/>
<r a="/good_url.html"/>
<r a="/some_uri_with_html/%2e%2e%2f%2eini"/>
</rows>

So, all fine except for the Ampersand, which seems to be converted from entity to single char somewhere in the process.

In other words, I would need to get

<r a="/good_url.html?something=one&amp;something_else=four"/>

Any advice ?

Thanks in advance !

Upvotes: 1

Views: 1609

Answers (2)

Aacini
Aacini

Reputation: 67296

@echo off & setLocal enableDELAYedexpansion

set "find=&"
set "replace=&amp;"

> test.xml (
   echo ^<rows^>
   for /f "tokens=5" %%A in ('findstr /v "string1 string2" test.log') do (
      set "string=%%A"
      set "string=!string:%find%=%replace%!"
      echo ^<r a="!string!"/^>
   )
   echo ^</rows^>
)

Output:

<rows>
<r a="/good_url.html?something=one&amp;something_else=four"/>
<r a="/good_url.html"/>
<r a="/some_uri_with_html/%2e%2e%2f%2eini"/>
</rows>

Upvotes: 1

Stephan
Stephan

Reputation: 56238

Escaping the & is not needed, if you use this syntax for set:

set "var=value"

Here is the adapted code:

setlocal enabledelayedexpansion
set "find=&"
set "replace=&.amp;"
for %%A in ("Hello & World") do (
  set string=%%~A
  call set "string=%%string:!find!=!replace!%%"
  echo ^<r a="!string!"/^>
)

Upvotes: 0

Related Questions