You are not logged in.

#1 16 Apr 2007 22:14

Freak
Member
Registered: 16 Apr 2007
Posts: 2

Search and replace

Howdy,

I have been doing some searching on the internet on how to use CMD to find and replace a text string within a .txt document, and not really getting any where fast.

With out knowing anything at all about command promt - well a bit more than your basic user - I have com up with this:

::Delete the character string 'ab'
SET _test="cabby"
SET _result=%_test:ab=%

Childs play, I know. But is there a way that I can change the word "cabby" to a text file and then have the batch file search the file and delete ab from it as well as saving the file (even better if it can save the file under a different file name).

Thanks alot for any help you guys can give

David

Offline

#2 17 Apr 2007 14:22

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Search and replace

Using "cmd" native commands is perhaps not the best way to achieve this, since processing a large file could take quite some time.  Furthermore the search/replace facility provided with "set" is not case sensitive.  I'd typically use a Windows port of "sed" for this kind of thing ... much quicker and way more powerful.

http://www.google.co.uk/search?q=Win32%20port%20sed

But to answer you in the manner requested...

@echo off

set input=Z:\somedir\YourInputFile.txt
set output=Z:\somedir\YourOutputFile.txt

set find=cabby
set repl=cby

type nul >"%output%"

for /f "usebackq tokens=*" %%A in ("%input%") do (
    call :process %%A >> "%output%"
)

goto :EOF

:process

set line=%*
call echo:%%line:%find%=%repl%%%

goto :EOF

NB - As a side effect of the way "for" works, blank lines will be lost.  And characters which "cmd" deems to be "special" in the data file might cause problems. e.g. & < > ^ %

Last edited by bluesxman (17 Apr 2007 14:22)


cmd | *sh | ruby | chef

Offline

#3 17 Apr 2007 22:43

Freak
Member
Registered: 16 Apr 2007
Posts: 2

Re: Search and replace

thanks very much for your reply - will definately help me in the future smile
as for sed will look into that.

cheers again.

Offline

Board footer

Powered by