Question

I need a batch file that will find and replace text in a text file!

Asked by: Caiapfas

Could anyone help me make a Btch file that will find and replace text IN a text file?


thx you,
support@ticketstogo.com

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-03-09 at 14:17:33ID20913053
Tags

file

,

replace

,

text

,

batch

,

find

Topics

Miscellaneous Programming

,

Windows Batch Scripting

Participating Experts
4
Points
125
Comments
31

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. find and replace
    Hello, I need to open an html file and then do 'find and replace'. Can anyone tell me how I can do this? Thanks.
  2. batch find string and replace
    I am trying to do a find and replace using batch commands. I am on windows NT and the file is a text file such as: WRRECV0028820 7134651234R02121000 000002781812100271346512343200000030475 ...
  3. Find and Replace
    Dear friends, Again me! It is possible find word or phrase in any file and REPLACE IT? Thank you in advance, Dict
  4. Find/Replace Procedure for text within procedure
    I have a script that returns lines of code that include a defined text string. I am wondering if anyone knows of a reasonable way to add a replace feature to work along with that code. Here is my 'find' query: SELECT NAME, line, text FROM user_source WHERE text like '%te...
  5. Find and replace text string using batch file
    Can anyone tell me how I go about getting a batch file to look for a particular text string in a file and then replacing it with something else? I am exporting part of the registry into a text file and would like HKEY_LOCAL_MACHINE to become HKEY_CURRENT_USER wherever it exi...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: FishMongerPosted on 2004-03-09 at 17:12:25ID: 10556665

The answer is Yes, BUT we need more info before we can help you.

 

by: mario73Posted on 2004-03-09 at 18:01:22ID: 10557004

Does it have to be a Batch file?  This is something that would be relatively simple using a VB script.......if VBS is OK, let me know some more details and I will post something.

Greg

 

by: CaiapfasPosted on 2004-03-10 at 06:30:21ID: 10560892

Ok, I need it to replace all the text "TBA" in a .txt file with 12:00am text . I need it to be a batch file.

 

by: lbertaccoPosted on 2004-03-10 at 07:40:45ID: 10561611

This is not possible. The batch processor and command line tools of Windows are too limited. There is no way to perform a saerch&replace.
To accomplish this you either need an additional (command line) utility for search&replace that you can call from within your batch OR you have to forget about .bat files and use the Windows Script Host (scripts written in VBScript or JScript). These are .vbs or .js script files that can be launched exactly like the .bat files in the latest versions of windows without additional software and supporting much wider functionalities than batches.

 

by: chandrabothPosted on 2004-03-10 at 23:09:31ID: 10568295

could you send me the file?

 

by: chandrabothPosted on 2004-03-10 at 23:09:47ID: 10568298

could you send me the file? proxy@everyday.com.kh

 

by: CaiapfasPosted on 2004-03-11 at 06:46:58ID: 10571664

ok, could you help me make a javascript file .js that will do the find and replace (find TBA and replace with 12:00am)job within the .txt file and copy it form c:\web to c:\cweb

thanx for you help!

 

by: lbertaccoPosted on 2004-03-11 at 13:03:11ID: 10575422

here is the script. You can run it with
C:> cscript <scriptname>
or just typyng <scriptname> but in this case the messages may displayed in windows message boxes and you might prefer to remove them (since they wait for the user too click on "OK").

---------
var srcFolder = "C:\\Web";
var dstFolder = "C:\\CWeb";

var fso =new ActiveXObject("Scripting.FileSystemObject");
if(!fso.FolderExists(srcFolder)) {
  WScript.Echo("Source folder (" + srcFolder + ") doesn't exist!");
  WScript.Quit(1);
}
if(!fso.FolderExists(dstFolder)) {
  WScript.Echo("Destination folder (" + dstFolder + ") doesn't exist!");
  WScript.Quit(1);
}

var fc = new Enumerator(fso.GetFolder(srcFolder).files);
while(!fc.atEnd()) { //for each file in srcFolder
  var fname = fc.item().name;  
  if(fname.match(/\.txt$/)) { //only consider .txt files
    WScript.Echo("Processing " + fname + "...");
    var srcfile = fc.item().OpenAsTextStream(1);
    var srctext = srcfile.AtEndOfStream ? "" : srctext=srcfile.ReadAll();
    srcfile.close();
    var dstfile = fso.CreateTextFile(fso.BuildPath(dstFolder, fname), true);
    dstfile.write(srctext.replace(/TBA/g, "12:00am"));    
    dstfile.close();
  }
  fc.moveNext();
}

 

by: lbertaccoPosted on 2004-03-11 at 13:14:03ID: 10575539

I forgot to say that you have to name the file with the script "whatever.js"

 

by: CaiapfasPosted on 2004-03-11 at 13:32:19ID: 10575692

ok, one last thing before I GTG, I need it to find a text file called My Tickets.txt in c:\web then after the find and replace, rename it to TTTickets.txt and copy it to c:\cweb

thx you so much for your help alrdy!!

 

by: CaiapfasPosted on 2004-03-11 at 13:42:49ID: 10575793

also, I'm getting cscript is not a program internal or external?

 

by: lbertaccoPosted on 2004-03-11 at 13:58:07ID: 10575929

Cscript is an external command ususally located in C:\Windows\System32 (if you have win2k or xp).

For the *ticket thing just replace the line "var dstfile=..." with:
    var dstfname= fname == "My Tickets.txt" ? "TTTickets.txt" : fname;
    var dstfile = fso.CreateTextFile(fso.BuildPath(dstFolder, dstfname), true);

BTW, note that this script doesn't modify the files in C:\Web. It only reads tesxt files from C:\Web, do the search&replace in memory and save the results in C:\CWeb\something.txt. Hope this is what you wanted.

 

by: CaiapfasPosted on 2004-03-11 at 14:21:12ID: 10576137

ok, its almost working perfectly, but its not renaming, its only making the new file as MyTickets.txt in the correct directory? instead of TTTickets.txt

 

by: CaiapfasPosted on 2004-03-11 at 20:36:37ID: 10578031

Sorry, let me clarify. It is doing the find and replace and copying the file perfectly, but it isnt renaming the file to TTTickets.txt. It is removing the space, so it looks like this MyTickets.txt

 

by: lbertaccoPosted on 2004-03-11 at 23:09:48ID: 10578610

Mmh, I dont understand. What do you mean with "It is removing the space" ?. My script doesn;t change the name of the file "My Tickets.txt" in C:\Web. It just creates a file named "TTTickets.txt" in C:\CWeb with the result of the search&replace of My Tickets.txt.

Anyway if you want the file C:\Web\My Tickets.txt renamed, change the script like this
-----------
var srcFolder = "C:\\Web";
var dstFolder = "C:\\CWeb";

var fso =new ActiveXObject("Scripting.FileSystemObject");
if(!fso.FolderExists(srcFolder)) {
  WScript.Echo("Source folder (" + srcFolder + ") doesn't exist!");
  WScript.Quit(1);
}
if(!fso.FolderExists(dstFolder)) {
  WScript.Echo("Destination folder (" + dstFolder + ") doesn't exist!");
  WScript.Quit(1);
}

var fc = new Enumerator(fso.GetFolder(srcFolder).files);
while(!fc.atEnd()) { //for each file in srcFolder
  var fname = fc.item().name;  
  if(fname.match(/\.txt$/)) { //only consider .txt files
    WScript.Echo("Processing " + fname + "...");
    if(fname == "My Tickets.txt") fc.item().move(fname="TTTickets.txt");          
    var srcfile = fc.item().OpenAsTextStream(1);
    var srctext = srcfile.AtEndOfStream ? "" : srctext=srcfile.ReadAll();
    srcfile.close();    
    var dstfile = fso.CreateTextFile(fso.BuildPath(dstFolder, fname), true);
    dstfile.write(srctext.replace(/TBA/g, "12:00am"));    
    dstfile.close();
  }
  fc.moveNext();
}
------
Note that this script just renames the file "My Tickets.txt" in c:\web but doesn't change its content. Only the file TTTickets in C:\CWeb will be changed. If this is not what you wanted, please try to be more precise in your request.

 

by: CaiapfasPosted on 2004-03-12 at 07:14:05ID: 10581111

PERFECT, I'm very sorry I wasn't more specific. My first time using Expert Exchange. I only hope that I can sit down and write a javascript like that , so quickly oneday. I love javascript,I always have. any tips on how to learn it more quickly and completely?

Also, one last question about the script! Can it load a program called c:\cweb\openfeed.exe??? which uploads the text file?


Thank you so much!
Caiapfas
support@ticketstogo.com

 

by: lbertaccoPosted on 2004-03-12 at 07:44:52ID: 10581386

Yes, you can find full Windows Script Host documentation and an introduction to jscript at www.microsoft.com/scripting (see links "JScript Documentation" and "Windows Script Host Documentation", these are also available for download using the last 2 links in the same page).
For the execution of openfeed, follow these links (again from the same page mentioned above): Windows Script Host Documentation -> Reference ->Methods -> Run Method. It also has two examples at the end. The equivalent Jscript code (for example 1) is:
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "%windir%\notepad " + WScript.ScriptFullName;

 

by: CaiapfasPosted on 2004-03-12 at 08:11:28ID: 10581676

ok, i don't understand . I when to the above site , but only found VBscript?

how can i make this
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "%windir%\notepad " + WScript.ScriptFullName;


run c:\cweb\opfeed.exe?

var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "C:\\cweb\openfeed.exe " + WScript.ScriptFullName;

and if that is it , when do i add it to the script?

 

by: lbertaccoPosted on 2004-03-12 at 08:43:25ID: 10581994

Almost:
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "C:\\cweb\\openfeed.exe";

Regarding the position where to insert this piece in the orginal script, it depends on when you want it executed. If you want it executed at the end,after the search&replace thing, just add it at the very end of the file.

These are the links that I see at www.microsoft.com/scripting:
 Script Debugger Documentation
 Remote Scripting Documentation
 JScript Documentation
 VBScript Documentation  
 Windows Script Host Documentation  
 Windows Script Components Documentation  
 Microsoft Windows Script 5.6 Documentation for Download
 Microsoft Windows Script 5.6 Download
The third is javascript.

 

by: CaiapfasPosted on 2004-03-12 at 08:59:06ID: 10582184

Your a JavaScript god! If i Had more points I would surely load you up! Might I ask what books, sites you recomend?

 

by: CaiapfasPosted on 2004-03-12 at 09:04:23ID: 10582243

I know its due to my stupidity, but i'm getting a error. problay due to where I'm putting the run command.

var srcFolder = "Z:\\web";
var dstFolder = "C:\\cweb";

var fso =new ActiveXObject("Scripting.FileSystemObject");
if(!fso.FolderExists(srcFolder)) {
  WScript.Echo("Source folder (" + srcFolder + ") doesn't exist!");
  WScript.Quit(1);
}
if(!fso.FolderExists(dstFolder)) {
  WScript.Echo("Destination folder (" + dstFolder + ") doesn't exist!");
  WScript.Quit(1);
}

var fc = new Enumerator(fso.GetFolder(srcFolder).files);
while(!fc.atEnd()) { //for each file in srcFolder
  var fname = fc.item().name;  
  if(fname.match(/\.txt$/)) { //only consider .txt files
    WScript.Echo("Processing " + fname + "...");
    if(fname == "MyTickets.txt") fc.item().move(fname="TTTickets.txt");        
    var srcfile = fc.item().OpenAsTextStream(1);
    var srctext = srcfile.AtEndOfStream ? "" : srctext=srcfile.ReadAll();
    srcfile.close();    
    var dstfile = fso.CreateTextFile(fso.BuildPath(dstFolder, fname), true);
    dstfile.write(srctext.replace(/TBA/g, "12:00am"));    
    dstfile.close();
  }
  fc.moveNext();
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "C:\\cweb\\openfeed.exe";

 

by: lbertaccoPosted on 2004-03-12 at 09:11:26ID: 10582312

You have removed one "}" at the end. The file should end like:
...
  }
  fc.moveNext();
}
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "C:\\cweb\\openfeed.exe";

 

by: CaiapfasPosted on 2004-03-12 at 09:25:21ID: 10582463

I'm very sorry, I know i'm driving you nuts

But I'm still getting the error?

var srcFolder = "Z:\\web";
var dstFolder = "C:\\cweb";

var fso =new ActiveXObject("Scripting.FileSystemObject");
if(!fso.FolderExists(srcFolder)) {
  WScript.Echo("Source folder (" + srcFolder + ") doesn't exist!");
  WScript.Quit(1);
}
if(!fso.FolderExists(dstFolder)) {
  WScript.Echo("Destination folder (" + dstFolder + ") doesn't exist!");
  WScript.Quit(1);
}

var fc = new Enumerator(fso.GetFolder(srcFolder).files);
while(!fc.atEnd()) { //for each file in srcFolder
  var fname = fc.item().name;  
  if(fname.match(/\.txt$/)) { //only consider .txt files
    WScript.Echo("Processing " + fname + "...");
    if(fname == "MyTickets.txt") fc.item().move(fname="TTTickets.txt");        
    var srcfile = fc.item().OpenAsTextStream(1);
    var srctext = srcfile.AtEndOfStream ? "" : srctext=srcfile.ReadAll();
    srcfile.close();    
    var dstfile = fso.CreateTextFile(fso.BuildPath(dstFolder, fname), true);
    dstfile.write(srctext.replace(/TBA/g, "12:00am"));    
    dstfile.close();
 }
  fc.moveNext();
}
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run "C:\\cweb\\openfeed.exe";

 

by: lbertaccoPosted on 2004-03-12 at 09:49:39ID: 10582723

My mistake, change last line to:
WshShell.Run("C:\\cweb\\openfeed.exe");

 

by: CaiapfasPosted on 2004-03-12 at 10:34:21ID: 10583153

ok, I'm getting (Null) The system cannot find the file specified.
I know the path is correct

 

by: lbertaccoPosted on 2004-03-12 at 10:45:27ID: 10583245

Probably not, the path must be wrogn: check if it's C: or Z: and use double backslashes "C:\\...", laso check if openfeed is actually a .exe file. I tested the script and works fine.

 

by: CaiapfasPosted on 2004-03-12 at 11:06:23ID: 10583442

openfeed is a .exe
this is cut n pasted from explorer - openfeed.exe
I even tried to make the script use a batch file to open the .exe, same error as above?

var srcFolder = "Z:\\";
var dstFolder = "C:\\Program Files\\Openfield Technologies\\OpenFeed\\";

var fso =new ActiveXObject("Scripting.FileSystemObject");
if(!fso.FolderExists(srcFolder)) {
  WScript.Echo("Source folder (" + srcFolder + ") doesn't exist!");
  WScript.Quit(1);
}
if(!fso.FolderExists(dstFolder)) {
  WScript.Echo("Destination folder (" + dstFolder + ") doesn't exist!");
  WScript.Quit(1);
}

var fc = new Enumerator(fso.GetFolder(srcFolder).files);
while(!fc.atEnd()) { //for each file in srcFolder
  var fname = fc.item().name;  
  if(fname.match(/\.txt$/)) { //only consider .txt files
    WScript.Echo("Processing " + fname + "...");
    if(fname == "MyTickets.txt") fc.item().move(fname="TTTickets.txt");        
    var srcfile = fc.item().OpenAsTextStream(1);
    var srctext = srcfile.AtEndOfStream ? "" : srctext=srcfile.ReadAll();
    srcfile.close();    
    var dstfile = fso.CreateTextFile(fso.BuildPath(dstFolder, fname), true);
    dstfile.write(srctext.replace(/TBA/g, "12:00am"));    
    dstfile.close();
 }
  fc.moveNext();
}
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.Run("C:\\Program Files\\Openfield Technologies\\OpenFeed\\openfeed.exe");

 

by: CaiapfasPosted on 2004-03-12 at 11:08:48ID: 10583462

oo yea, openfeed has to open up then it goes to the system tray, would this effect it? If so why won't the batch file work, it does when i load it just from the batch file?

 

by: lbertaccoPosted on 2004-03-12 at 11:53:31ID: 10583865

Try replacing the last line with:
WshShell.Run("C:\\Windows\\Notepad.exe");

If at the end of the script you see notepad starting without errors then the script is fine and the issue is with your openfeed application.
In any case:
- you probably should open a new request since this is not related to search&replace anymore
- maybe openfeed is not supposed to be used in batch processing but only interactively
- if you still have issues, report exactly the error you are receiving and which program is giving the error. I believe that you are not getting the error from the script but from openfeed. Also try to start openfeed manually from the command prompt and see what happens.

 

by: FishMongerPosted on 2004-03-12 at 14:30:49ID: 10585011

I've been tied up with several projects, so I haven't had a chance to give any input.  It looks like lbertacco has got you pretty well covered, but if for future reference here's a Perl solution.  This assumes that the script is being run in the same directory as the source files; if it's not, then we'll need to make a minor change.

#!perl -w

{local $^I = '.orig';
@ARGV = glob("*.txt");
while (<>) { s/\bwas\b/is/ig; print; } }
@orig = glob("*.orig");
unlink @orig;
system "move Tickets.txt c:/cweb/TTTickets.txt" if (-e 'Tickets.txt');


I love the power of Perl!

 

by: FishMongerPosted on 2004-03-12 at 14:33:36ID: 10585026

Oops I forgot to adjust for my test script.

while (<>) { s/\bwas\b/is/ig; print; } }

should be

while (<>) { s/\bTBA\b/12:00am/ig; print; } }

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...