Как заменить строки в файле в командной строке

В стандартный инструментарий Windows не входит средство, позволяющее заменить одну строку в файле на другую. Описанный здесь скрипт для обработки файлов позволяет решить  задачу замены строк в текстовом файле.

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.



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.

Скрипт для обработки файлов

'Replace Text

'Written by: Jason Faulkner

'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

Set oFSO = CreateObject("Scripting.FileSystemObject")

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

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

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


Другой вариант скрипта для обработки файлов

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"ex3")> 0 Then
    	strLine = Replace(strLine,"ex3","ex5")
    End If 
    WScript.Echo strLine

Данный скрипт прочитывает по очереди все строки исходного файла, при необходимости заменяет в них текст и выводит на стандартный вывод. Если нужно не просто вывести строки, а сохранить их в файле — используйте перенаправление вывода.

Сохраните скрипт в myreplace.vbs и используйте в командной строке:

c:\test> cscript /nologo myreplace.vbs  > newfile
c:\test> ren newfile file.txt

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *