Saturday 29 August 2015

VBScript: To replace certain text from all the text files placed in certain folder

'' Save the code as ModifyTextFiles.vbs and place it in a folder where all your text files are placed.
''When double clicked, it will ask for two inputs: 1. Search String and 2. Replace with String.

''eg: if my first input i.e. Search String="Venu" and 2nd input Replace_with_String= "Gopi", then
'' it will remove all the occurances of string "Venu" with "Gopi" and it will be replaced from all the text files..
''Note: Before running this, please take the back up of your base txt files.

fldPath=getAbsPath()
FindStr= InputBox("What do you want to replace?", "Enter Search String")    
ReplStr=InputBox("What do you want to replace with?", "Replace with this String")
Set fso=CreateObject("Scripting.FileSystemObject")
If fso.FolderExists(fldpath) Then
    Set fold=fso.GetFolder(fldpath)
    Set allFiles=fold.Files
    For Each fil In allFiles
        If LCase(fso.GetExtensionName(fil.Path))="txt" Then
            fpath=fil.Path
            'MsgBox fpath
            Call UpdateFileData(fpath, FindStr, ReplStr)
        End If
    Next
    Msgbox "All the text files are updated.."    
End If
Set fso=Nothing

Function UpdateFileData(fPath, FindStr, ReplStr)
    If FindStr<>"" Then
        fData=""
        Set fso1=CreateObject("Scripting.FileSystemObject")
        Set fr= fso1.OpenTextFile(fPath)    '' Read File
        Do Until fr.AtEndOfStream        '' Until the end of the File..
            lin= fr.ReadLine
            If lin<>"" And InStr(1, lin, FindStr, 1)>0 And Len(lin)>0 Then                
                'lin=Replace (lin, chr(34)&FindStr&chr(34), ReplStr, 1, -1, 1)
                lin=Replace (lin, FindStr, ReplStr, 1, -1, 1)
                fData=fData & lin & vbcrlf
            else
                fData=fData & lin & vbCrLf
            End If
'            lin=""
        Loop
        fr.Close
        'MsgBox fpath
        Set fw=fso1.OpenTextFile(fPath, 2, True)    '' For file wtring..
        fw.Write fData
        fw.Close
    End If                
End Function

Function getAbsPath()
   getAbsPath=""
   Set fso=CreateObject("Scripting.FileSystemObject")
   getAbsPath=fso.GetAbsolutePathName(".")
   Set fso=Nothing
End Function
'msgbox chr(34)= "

No comments:

Post a Comment