Find and replace text

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
Lateralus138
Posts: 11
Joined: 17 Aug 2009 13:18
Location: Decatur, Il.
Contact:

Find and replace text

#1 Post by Lateralus138 » 08 Apr 2013 12:21

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.

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: Find and replace text

#2 Post by Endoro » 08 Apr 2013 14:36

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!


Lateralus138
Posts: 11
Joined: 17 Aug 2009 13:18
Location: Decatur, Il.
Contact:

Re: Find and replace text

#3 Post by Lateralus138 » 08 Apr 2013 14:47

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.

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: Find and replace text

#4 Post by Endoro » 08 Apr 2013 14:58

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.

Lateralus138
Posts: 11
Joined: 17 Aug 2009 13:18
Location: Decatur, Il.
Contact:

Re: Find and replace text

#5 Post by Lateralus138 » 08 Apr 2013 15:17

Awesome!! Worked perfectly! Now I'll create adifferent version based on this to better suit my needs, much appreciated.

Post Reply