• ARTICLES
SEARCH

How-To Geek

Replace Text in Plain Text Files from the Command Line

A very useful function which is missing from the Windows library of command line tools is the ability to replace text in plain text files. A function like this can be used for a variety of practical tasks which many system admin’s perform, such as:

  • Update configuration/INI files to replace UNC paths.
  • Mass update user information stored in INI files on a Terminal/Citrix server.
  • Use in conjunction with scripts to deploy ‘templated’ data and then apply values to the copied files.

Our solution is a VBScript which interfaces with the Visual Basic Replace function. By placing this script into a location in your Windows PATH variable, you now have this functionality available at your disposal.

Uses

Once on your system, you can call the script by simply using the ReplaceText command. A few examples will illustrate ways you can use this:

Replace the word “null” with “n/a” in the C:DataValues.csv file:

ReplaceText “C:DataValues.csv” null n/a

Scan all INI files in the C:Users (+ sub directories) folder replacing all occurrences of “Server=Old” with “Server=New” using a case insensitive search:

FORFILES /P “C:Users” /M *.ini /S /C “Cmd /C ReplaceText @path Server=Old Server=New /I”

Scan all CFG files in the current user’s profile replacing “p@ssw0rd” with “PA$$woRd” using a case sensitive search:

FORFILES /P “%UserProfile%” /M *.cfg /S /C “Cmd /C ReplaceText @path p@ssw0rd PA$$woRd”

As you can see below, the script is very simple and can easily be modified to accommodate any special situations you may have. Alternately, you may want to create copies of the script which hardcode particular values so you can execute the command with a double-click and/or allow you to easily distribute it to others.

The Script

'Replace Text
'Written by: Jason Faulkner
'SysadminGeek.com

'This script should be placed in a folder specified in your system's PATH variable.

'Usage (WScript):
'ReplaceText FileName OldText NewText [/I]

' /I (optional) - Text matching is not case sensitive

Set oArgs = WScript.Arguments

intCaseSensitive = 0
For i = 3 to oArgs.Count-1
    If UCase(oArgs(i)) = "/I" Then intCaseSensitive = 1
Next

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FileExists(oArgs(0)) Then
    WScript.Echo "Specified file does not exist."
Else
    Set oFile = oFSO.OpenTextFile(oArgs(0), 1)
    strText = oFile.ReadAll
    oFile.Close

    strText = Replace(strText, oArgs(1), oArgs(2), 1, -1, intCaseSensitive)

    Set oFile = oFSO.OpenTextFile(oArgs(0), 2)
    oFile.WriteLine strText
    oFile.Close
End If


Additional Notes

By default, Windows uses WScript to execute VBScript (VBS) files. The only problem this can cause is any errors and/or messages from the script will appear as popup boxes. For a command line tool, it is best these messages be displayed in the console. There are a couple of ways you can accomplish this.

Change the default handler of VBScript files to CScript by running this command from command prompt (with Administrator rights):

CScript //H:CScript

Run the ReplaceText script explicitly using the CScript command:

CScript “C:PathToReplaceText.vbs” //B FileName OldText NewText [/I]

As a special case, executing ReplaceText from a batch script typically implies CScript as the engine used regardless of the default handler. You will definitely want to test this though prior to relying on this functionality.

 

Download ReplaceText Script from SysadminGeek.com

Jason Faulkner is a developer and IT professional who never has a hot cup of coffee far away. Interact with him on Google+

  • Published 08/30/10

Comments (8)

  1. Chris K

    Such timing.

    I was pondering something just like this and was planning on building a little app to plow through hundreds of directories updating a config line in a specifically named text file. It looks like you’ve done it for me.

    Thanks!

  2. Wil

    This type of thing i recon is where powershell comes into a sysadmin’s tools.

    You could do this with a single command line:

    Get-Content .test.txt | ForEach-Object {$_ -replace “foo”, “bar”} | Set-Content .test2.txt

  3. Wil

    Not to mention powershell is now part of windows (since it comes default with windows 7 and Windows 2008 R2).

  4. Street

    Well regarding powershell i have been messing around with it for the better part of the day.
    As it will work but there are very specfic problems to powershell not to mention policy rights.
    This script does work and it works well and it is much simpler to use then powershell.
    IMO powershell has some major fall backs its limitations might be greater but it is a burden none the less. that line of code listed above for powershell is not only longer then just calling replacetext it also cant be called directly from another file with out some major codeing invloved.
    I see no reason to use powershell for this purpose. It might have some significant useage in system admin but outside of that powershell just falls short on so many things.

  5. Street

    I was wondering is there any way to use this with nested quotes
    Example would be
    this is the text
    bobby is “a fun person”
    Change text too
    bobby is “not a fun person”

  6. LA_DOS

    I’m getting message ‘FORFILES’ is not recognized as an internal or external command,operable program or batch file.

    I placed the code in PATH variable & the ReplaceText works great but the FORFILES is not working.Could you please provide more inputs on how to execute this one.

    I ran ReplaceText from the command prompt & it runs great. FORFILE is the issue

  7. LA_DOS

    I’m using Windows XP professional – SP2

  8. Ahmad Belal

    I don’t know how to thank you. You helped me a lot.
    Can I use Write method instead of WriteLine to prevent adding an extra line at the end of the text or it will make problems?
    Help me. I’m a doctor but I really needed this script. Thanks.

Enter Your Email Here to Get Access for Free:

Go check your email!