ASHU MAWALKAR
ASHU MAWALKAR

Reputation: 19

Batch Commands to find and Replace string

I want batch commands to find and replace string in word file and also renaming that file with same string and that too for a folder.

Multiple files needs to be searched and replaced with string and at the same time file name should be checked also.

Upvotes: 1

Views: 776

Answers (2)

shadow2020
shadow2020

Reputation: 1351

Here is a macro script by Allen Wyatt that can do this. Source

Public Sub MassReplace()
    With Application.FileSearch
        .LookIn = "C:\"             ' where to search
        .SearchSubFolders = True    ' search the subfolders
        .FileName = "*.doc"         ' file pattern to match

        ' if more than one match, execute the following code
        If .Execute() > 0 Then
            ' for each file you find, run this loop
            For i = 1 To .FoundFiles.Count
                ' open the file based on its index position
                Documents.Open FileName:=.FoundFiles(i)

                ' search and replace the address
                selection.Find.ClearFormatting
                selection.Find.Replacement.ClearFormatting
                With selection.Find
                    .Text = "OldAddress"
                    .MatchCase = True
                    .Replacement.Text = "NewAddress"
                End With
                selection.Find.Execute Replace:=wdReplaceAll

                ' replace e-mail address
                With selection.Find
                    .Text = "Oldemail"
                    .Replacement.Text = "Newemail"
                End With
                selection.Find.Execute Replace:=wdReplaceAll

                ' save and close the current document
                ActiveDocument.Close wdSaveChanges
            Next i
        Else
            ' if the system cannot find any files
            ' with the .doc extension
            MsgBox "No files found."
        End If
    End With
End Sub

Change these 3 lines based on your own needs:

.LookIn = "C:\"             ' where to search
.SearchSubFolders = True    ' search the subfolders
.FileName = "*.doc"         ' file pattern to match

Aside from that, doing this from batch file (specifically because you are talking word documents) is outside of CMD's abilities.

Upvotes: 0

Floempi
Floempi

Reputation: 36

There exists no integrated funtction in batch. Powershell has such functions, but i would consider using fart.exe, which is easier to use.

Here is the link -> http://fart-it.sourceforge.net/

//EDIT: Looks like i have not recognized the "word file". If thats the case i don't know any possibility to do this with batch/cmd.

Upvotes: 1

Related Questions