Help with string replace

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Melanie
Posts: 3
Joined: 13 Mar 2013 23:00

Help with string replace

#1 Post by Melanie » 13 Mar 2013 23:14

Dear Guys,

I am trying to convert/replace a part in a long txt file.
<icon>http://www.example.com/img.jpg</icon> to <icon src="img.jpg" />
I managed to replace everything except signs like < > = using this code:

@echo off
setlocal enabledelayedexpansion
set "filename=C:\ProgramData\example.txt"
set "tempfile=C:\ProgramData\output.txt"
for /F "delims=" %%a in (%filename%) do (
set text=%%a
set text=!text:^http://www.example.com/=!
echo !text!>>%tempfile%
)

Does someone know how to improve that code in an easy way? Because as soon as I use this code I get an error: set text=!text:^<icon=<icon src="!
Melanie

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Help with string replace

#2 Post by foxidrive » 14 Mar 2013 00:13

SED is a commonly tool used for text manipulations, using regular expressions.
It could be done using WSH/VBS too and regular expressions.

Did you want to replace one specific set of text or every occurrence, and is the name always img.jpg?

To do it in plain batch will take some extra steps and knowing the makeup of the file is usually important.

Melanie
Posts: 3
Joined: 13 Mar 2013 23:00

Re: Help with string replace

#3 Post by Melanie » 14 Mar 2013 00:25

it has many occurences and the names of the images changes, however <icon>http://www.example.com/ stays the same and </icon> too. I would like to do it in batch since it is just a part of a batch programm

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Help with string replace

#4 Post by foxidrive » 14 Mar 2013 00:47

This seems to work here.

Code: Select all

@echo off
echo ^<icon^>http://www.example.com/img.jpg^</icon^>>example.txt
echo ^<icon^>http://www.example.com/img234.jpg^</icon^>>>example.txt
echo ^<icon^>http://www.example.com/123img.jpg^</icon^>>>example.txt
echo ^<icon^>http://www.example.com/imgbbb.jpg^</icon^>>>example.txt
echo ^<icon^>http://www.example.com/imgaaa.jpg^</icon^>>>example.txt

 
@echo off
setlocal enabledelayedexpansion
set "filename=C:\ProgramData\example.txt"
set "tempfile=C:\ProgramData\output.txt"

set "filename=example.txt"
set "tempfile=output.txt"


for /F "delims=" %%a in (%filename%) do (
set "text=%%a"
set "text=!text:<icon>http://www.example.com/=!"
set "text=!text:</icon>=!"
set text=^<icon src="!text!" /^>
>>%tempfile% echo !text!
)

Melanie
Posts: 3
Joined: 13 Mar 2013 23:00

Re: Help with string replace

#5 Post by Melanie » 14 Mar 2013 01:12

it works!! I was missing the ^

many thanks^^

Post Reply