Solved

vb script to check for specific file in a folder and then open each file and replace a text in file.

Posted on 2012-03-09
4
287 Views
Last Modified: 2012-03-10
Hi,

I need a vb script that will check specific file, ex: all files that starts with a "D" and if it finds it i need to open that file and edit it to replace a specific character in the file.

Thanks
0
Comment
Question by:tvae
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 38

Expert Comment

by:Shift-3
ID: 37703757
Paste the script below into a text file with a .vbs extension.  Customize the value of the strFolder variable on line 1 with the location of the folder containing the files.  Customize the value of the strMask variable on line 2 with the file mask to search for.  Change the value of the blnRecurseSubfolders variable on line 3 to True if you wish to search for files in subfolders.  Customize the value of the strOldText variable on line 4 with the text to be replaced.  Customize the value of the strNewText variable on line 5 with the text with which to replace it.

Back up your files before running this, and ensure that it is performing exactly as you intend before using it with production data.  It will edit the files without any prompts or warnings.
strFolder = "c:\files"
strMask = "D*.txt"
blnRecurseSubfolders = False
strOldText = "the string to find"
strNewText = "the string to replace it with"

For Each strFile In DirToArray(strFolder, strMask, blnRecurseSubfolders)
    StringReplace strFile, strOldText, strNewText
Next

Function DirToArray(strRootFolder, strFileMask, blnRecurse)
    Dim strFolder, strCommand, objShell, objWshScriptExec
    Dim objStdOut, intLimit, strFile, arrOutput()
    
    If Right(strRootFolder, 1) = "\" Then
        strFolder = strRootFolder
    Else
        strFolder = strRootFolder & "\"
    End If

    strCommand = "%comspec% /c @dir " & Chr(34) &_
        strFolder & strFileMask & Chr(34) & " /a:-d /b"
        
    If blnRecurse Then
        strCommand = strCommand & " /s"
    End If

    Set objShell = CreateObject("WScript.Shell")
    Set objWshScriptExec = objShell.Exec(strCommand)
    Set objStdOut = objWshScriptExec.StdOut
    
    intLimit = 0

    Do Until objStdOut.AtEndOfStream
        strFile = objStdOut.ReadLine
        
        If Not blnRecurse Then
            strFile = strFolder & strFile
        End If
        
        ReDim Preserve arrOutput(intLimit)
        arrOutput(intLimit) = strFile
        intLimit = intLimit + 1
    Loop
    
    DirToArray = arrOutput
End Function

Sub StringReplace(strTextFile, strToFind, strToReplace)
    Const ForReading = 1
    Const ForWriting = 2
    Const TriStateUseDefault = -2
    Dim objFSO, objTextFile, strText, strNewText

    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objTextFile = objFSO.OpenTextFile(strTextFile, ForReading, False, TriStateUseDefault)
    strText = objTextFile.ReadAll
    objTextFile.Close

    strNewText = Replace(strText, strToFind, strToReplace, 1, -1, vbTextCompare)

    Set objTextFile = objFSO.OpenTextFile(strTextFile, ForWriting)
    objTextFile.Write strNewText
    objTextFile.Close
End Sub

Open in new window

0
 
LVL 54

Expert Comment

by:Bill Prew
ID: 37703959
Can you be more specific about:
I need a vb script that will check specific file, ex: all files that starts with a "D" and if it finds it i need to open that file and edit it to replace a specific character in the file.
Do you want to just look for matching files in a single folder, or recursively in child subfolder as well?

What do you mean by replace a specific character?  Is this like a search and replace, where all "A" characters become "B".   Or is this on a specific line, and at a specific position in the line?  Or what?

~bp
0
 
LVL 54

Accepted Solution

by:
Bill Prew earned 300 total points
ID: 37703985
Depending on the answers to my above questions, here's a starting shell of how I would approach it.
' Constants for I/O
Const ForReading = 1
Const ForWriting = 2

' Define folder to search
strBaseDir = "C:\temp\"

' Access the folder
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strBaseDir)

' Process each file in the folder
For Each objFile in objFolder.Files

    ' See if it matches the pattern of filenames we want
    If UCase(Left(objFile.Name, 1)) = "D" Then

        ' Read the entire file
        strFile = objFile.Path
        Set objReader = objFSO.OpenTextFile(strFile, ForReading)
        strData = objReader.ReadAll
        objReader.Close

        ' Make desired replacements in the file
        strData = Replace(strData, "A", "B")

        ' Write the updated data back to the file
        Set objWriter = objFSO.OpenTextFile(strFile, ForWriting, True)
        objWriter.Write strData
        objWriter.Close
    End If
Next

Open in new window

~bp
0
 
LVL 38

Expert Comment

by:Shift-3
ID: 37705539
Heh, well played.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Script to copy or move mouse-selected collection of files plus targets referenced by shortcuts (.lnk) The purpose of this article is to help illuminate the real challenges and options available (where they may exist) for utilizing simple scriptin…
With User Account Control (UAC) enabled in Windows 7, one needs to open an elevated Command Prompt in order to run scripts under administrative privileges. Although the elevated Command Prompt accomplishes the task, the question How to run as script…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question