Page 1 of 1

Find and replace text

Posted: 08 Apr 2013 12:21
by Lateralus138
I was wondering if someone could help me write a batch file to find and replace text in a text file. I have web urls on a website and need to replace 5 specific html codes with the real characters. The 5 things I need to change throughout the text file are as follows

Find Replace
---- -------
%26 = &
%2F = /
%3A = :
%3D = =
%3F = ?

I will keep adding new urls to a text file; say named a.txt or something and I want the batch to parse the text file and replace the characters... I learn better by using examples and experimenting with them so could someone please write this file for me and I can see how it works. I am fairly familiar with cmd and batch etc..., I've just never needed to do this before. I would appreciate any help.

Re: Find and replace text

Posted: 08 Apr 2013 14:36
by Endoro
It works as expected:

Code: Select all

@echo off&setlocal 
set "$11=%%26"
set "$12=%%2F"
set "$13=%%3A"
set "$14=%%3D"
set "$15=%%3F"
set "$21=&"
set "$22=/"
set "$23=:"
set "$24=="
set "$25=?"

setlocal enabledelayedexpansion
set "$31=!$11:%$11%=%$21%!"
set "$32=!$12:%$12%=%$22%!"
set "$33=!$13:%$13%=%$23%!"
set "$34=!$14:%$14%=%$24%!"
set "$35=!$15:%$15%=%$25%!"
set $
for /l %%i in (1,1,5) do echo(!$3%%i!


Re: Find and replace text

Posted: 08 Apr 2013 14:47
by Lateralus138
HI, thanks for the reply, but I am not sure how this is supposed to work. I tried just running this, then I tried placing this in the same folder as the text and running, then I tried using cmd to run this batch a.bat a.txt and it didn't work. Changed nothing in the text file. Is the ) missing at the end of your script? I tried with and and without it and it still did nothing.

Re: Find and replace text

Posted: 08 Apr 2013 14:58
by Endoro
This was an example. It works also on text files:

Code: Select all

@echo off&setlocal
set "file=test.txt"

(for /f "delims=" %%i in (%file%) do (
   set "line=%%i"
   setlocal enabledelayedexpansion
   set "line=!line:%%26=&!"
   set "line=!line:%%2F=/!"
   set "line=!line:%%3A=:!"
   set "line=!line:%%3D==!"
   set "line=!line:%%3F=?!"
   echo(!line!
   endlocal
))>%file%.new

Edit: delims added.

Re: Find and replace text

Posted: 08 Apr 2013 15:17
by Lateralus138
Awesome!! Worked perfectly! Now I'll create adifferent version based on this to better suit my needs, much appreciated.